8.16. AsyncIO Synchronization¶
8.16.1. Mutex Lock¶
Can be used to guarantee exclusive access to a shared resource
lock = asyncio.Lock() async with lock: # access shared state
8.16.2. Condition Object¶
cond = asyncio.Condition() async with cond: await cond.wait()
Manages an internal counter which is decremented by each
acquire()call and incremented by each
The counter can never go below zero.
acquire()finds that it is zero, it blocks, waiting until some task calls
sem = asyncio.Semaphore(10) async with sem: # work with shared resource
Can be used to notify multiple asyncio tasks that some event has happened.
wait()- Wait until the event is set. If the event is set, return
Trueimmediately. Otherwise block until another task calls
set()- Set the event. All tasks waiting for event to be set will be immediately awakened.
clear()- Clear (unset) the event. Tasks awaiting on
wait()will now block until the
set()method is called again.
Trueif the event is set.
import asyncio async def listener(event): print(f'Waiting for event') await event.wait() print(f'Event processed') async def main(): myevent = asyncio.Event() # Spawn a Task to wait until 'event' is set. handler = asyncio.create_task(listener(myevent)) # Sleep for 1 second and set the event. await asyncio.sleep(1) myevent.set() # Wait until processing is complete await handler asyncio.run(main()) # Waiting for event # Event processed