CKTIS / Python
asyncio.Lock
Ein gemeinsamer Lock gibt Tasks der asyncio-Schleife exklusiven Zugriff auf eine Ressource.
Version: Python 3.14; repository image, production runtime not attested
Syntax
async with asyncio.Lock(): ...Ein gemeinsamer Lock gibt Tasks der asyncio-Schleife exklusiven Zugriff auf eine Ressource.
Der Lock erfasst keinen Besitzer. Das Abbrechen eines in acquire wartenden Tasks gibt einen bereits von einem anderen belegten Lock nicht frei. Wartende acquire-Aufrufe kommen in der Reihenfolge ihres Wartens zum Zug. async with gibt auch bei Ausnahmen frei, daher im Beispiel True im Block und False nach ValueError. release bei freiem Lock löst RuntimeError aus.
Der Lock synchronisiert keine Betriebssystemthreads.
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())
Beispiele
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())
Ergebnis
True False
Der Lock synchronisiert keine Betriebssystemthreads.