CKTIS / Python
asyncio.Lock
Un Lock partagé réserve une ressource à une tâche de la boucle asyncio à la fois.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
async with asyncio.Lock(): ...Un Lock partagé réserve une ressource à une tâche de la boucle asyncio à la fois.
Le verrou ne mémorise pas de propriétaire. Annuler une tâche en attente dans acquire ne libère pas le verrou déjà acquis par une autre. Les appels acquire en attente passent dans leur ordre d’arrivée. async with libère aussi sur exception, d’où True dans le bloc et False après ValueError. Un release sur un verrou libre lève RuntimeError.
Ce verrou ne synchronise pas les fils système.
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())
Exemples
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())
Résultat
True False
Ce verrou ne synchronise pas les fils système.