CKTIS / Python
asyncio.Lock
Allows only one coroutine at a time into a critical section guarded by the same asynchronous lock.
Version: Python 3.14; repository image, production runtime not attested
Syntax
async with asyncio.Lock(): ...Allows only one coroutine at a time into a critical section guarded by the same asynchronous lock.
An asynchronous context manager releases the lock on departure, including when the guarded code raises.
Guard a shared resource by giving every participating task the same Lock; only one task can hold it at a time. Waiting acquire calls proceed in arrival order. async with releases on exceptions, explaining the True then False output. Releasing an unlocked Lock raises RuntimeError. It is for asyncio tasks, not OS threads. Lock does not track an owner. Cancelling a waiting acquire does not release a lock already held by another task.
import asyncio
async def main():
lock = asyncio.Lock()
await lock.acquire()
order = []
async def take(i):
async with lock:
order.append(i)
a, b = [asyncio.create_task(take(i)) for i in (1, 2)]
await asyncio.sleep(0)
lock.release()
await asyncio.gather(a, b)
assert order == [1, 2]
try:
lock.release()
except RuntimeError:
pass
else:
raise AssertionError
asyncio.run(main())
import asyncio
async def main():
l = asyncio.Lock()
await l.acquire()
waiting = asyncio.create_task(l.acquire())
await asyncio.sleep(0)
waiting.cancel()
try:
await waiting
except asyncio.CancelledError:
pass
assert l.locked()
async def release_elsewhere():
l.release()
await asyncio.create_task(release_elsewhere())
assert not l.locked()
asyncio.run(main())
Examples
import asyncio
async def main():
lock = asyncio.Lock()
try:
async with lock:
print(lock.locked())
raise ValueError
except ValueError:
print(lock.locked())
asyncio.run(main())
Result
True False
Guard a shared resource by giving every participating task the same Lock; only one task can hold it at a time. Waiting acquire calls proceed in arrival order. async with releases on exceptions, explaining the True then False output. Releasing an unlocked Lock raises RuntimeError. It is for asyncio tasks, not OS threads. Lock does not track an owner. Cancelling a waiting acquire does not release a lock already held by another task.