Python 3.4+Async programmingterm
asyncio.Lock
synchronization
An asynchronous mutex: while one task holds the lock, the others wait at async with without blocking the event loop.
Syntax
lock = asyncio.Lock()
async with lock: ...
You need a lock only where an await sits between checking and updating shared state: without an await tasks do not switch and there is no race. threading.Lock in a coroutine stalls the whole loop and asyncio.Lock does not, but it is not thread-safe. It is not reentrant: a nested async with lock in the same task waits for itself forever. Acquire it only with async with — a plain with lock raises TypeError.
Examples
import asyncio
counter = 0
async def add(lock):
global counter
async with lock:
value = counter
await asyncio.sleep(0.01) # переключение здесь — без замка вышла бы гонка
counter = value + 1
async def main():
lock = asyncio.Lock()
await asyncio.gather(*(add(lock) for _ in range(5)))
print(counter) # → 5
asyncio.run(main())
# Python 3.11+
import asyncio
async def main():
lock = asyncio.Lock()
try:
with lock:
pass
except TypeError:
print('нужен async with') # → нужен async with
await asyncio.sleep(0.01)
asyncio.run(main())
See also
Open in the full glossarydocs.python.orgReport an inaccuracy