Synchronization Primitives¶
Source code:Lib/asyncio/locks.py
asyncio synchronization primitives are designed to be similar tothose of thethreading module with two important caveats:
asyncio primitives are not thread-safe, therefore they should notbe used for OS thread synchronization (use
threadingforthat);methods of these synchronization primitives do not accept thetimeoutargument; use the
asyncio.wait_for()function to performoperations with timeouts.
asyncio has the following basic synchronization primitives:
Lock¶
- classasyncio.Lock¶
Implements a mutex lock for asyncio tasks. Not thread-safe.
An asyncio lock can be used to guarantee exclusive access to ashared resource.
The preferred way to use a Lock is an
asyncwithstatement:lock=asyncio.Lock()# ... laterasyncwithlock:# access shared state
which is equivalent to:
lock=asyncio.Lock()# ... laterawaitlock.acquire()try:# access shared statefinally:lock.release()
Changed in version 3.10:Removed theloop parameter.
- asyncacquire()¶
Acquire the lock.
This method waits until the lock isunlocked, sets it tolocked and returns
True.When more than one coroutine is blocked in
acquire()waiting for the lock to be unlocked, only one coroutineeventually proceeds.Acquiring a lock isfair: the coroutine that proceeds will bethe first coroutine that started waiting on the lock.
- release()¶
Release the lock.
When the lock islocked, reset it tounlocked and return.
If the lock isunlocked, a
RuntimeErroris raised.
- locked()¶
Return
Trueif the lock islocked.
Event¶
- classasyncio.Event¶
An event object. Not thread-safe.
An asyncio event can be used to notify multiple asyncio tasksthat some event has happened.
An Event object manages an internal flag that can be set totruewith the
set()method and reset tofalse with theclear()method. Thewait()method blocks until theflag is set totrue. The flag is set tofalse initially.Changed in version 3.10:Removed theloop parameter.
Example:
asyncdefwaiter(event):print('waiting for it ...')awaitevent.wait()print('... got it!')asyncdefmain():# Create an Event object.event=asyncio.Event()# Spawn a Task to wait until 'event' is set.waiter_task=asyncio.create_task(waiter(event))# Sleep for 1 second and set the event.awaitasyncio.sleep(1)event.set()# Wait until the waiter task is finished.awaitwaiter_taskasyncio.run(main())
- asyncwait()¶
Wait until the event is set.
If the event is set, return
Trueimmediately.Otherwise block until another task callsset().
- set()¶
Set the event.
All tasks waiting for event to be set will be immediatelyawakened.
- clear()¶
Clear (unset) the event.
Subsequent tasks awaiting on
wait()will now block until theset()method is called again.
- is_set()¶
Return
Trueif the event is set.
Condition¶
- classasyncio.Condition(lock=None)¶
A Condition object. Not thread-safe.
An asyncio condition primitive can be used by a task to wait forsome event to happen and then get exclusive access to a sharedresource.
In essence, a Condition object combines the functionalityof an
Eventand aLock. It is possible to havemultiple Condition objects share one Lock, which allows coordinatingexclusive access to a shared resource between different tasksinterested in particular states of that shared resource.The optionallock argument must be a
Lockobject orNone. In the latter case a new Lock object is createdautomatically.Changed in version 3.10:Removed theloop parameter.
The preferred way to use a Condition is an
asyncwithstatement:cond=asyncio.Condition()# ... laterasyncwithcond:awaitcond.wait()
which is equivalent to:
cond=asyncio.Condition()# ... laterawaitcond.acquire()try:awaitcond.wait()finally:cond.release()
- asyncacquire()¶
Acquire the underlying lock.
This method waits until the underlying lock isunlocked,sets it tolocked and returns
True.
- notify(n=1)¶
Wake upn tasks (1 by default) waiting on thiscondition. If fewer thann tasks are waiting they are all awakened.
The lock must be acquired before this method is called andreleased shortly after. If called with anunlocked locka
RuntimeErrorerror is raised.
- locked()¶
Return
Trueif the underlying lock is acquired.
- notify_all()¶
Wake up all tasks waiting on this condition.
This method acts like
notify(), but wakes up all waitingtasks.The lock must be acquired before this method is called andreleased shortly after. If called with anunlocked locka
RuntimeErrorerror is raised.
- release()¶
Release the underlying lock.
When invoked on an unlocked lock, a
RuntimeErrorisraised.
- asyncwait()¶
Wait until notified.
If the calling task has not acquired the lock when this method iscalled, a
RuntimeErroris raised.This method releases the underlying lock, and then blocks untilit is awakened by a
notify()ornotify_all()call.Once awakened, the Condition re-acquires its lock and this methodreturnsTrue.Note that a taskmay return from this call spuriously,which is why the caller should always re-check the stateand be prepared to
wait()again. For this reason, you mayprefer to usewait_for()instead.
Semaphore¶
- classasyncio.Semaphore(value=1)¶
A Semaphore object. Not thread-safe.
A semaphore manages an internal counter which is decremented by each
acquire()call and incremented by eachrelease()call.The counter can never go below zero; whenacquire()findsthat it is zero, it blocks, waiting until some task callsrelease().The optionalvalue argument gives the initial value for theinternal counter (
1by default). If the given value isless than0aValueErroris raised.Changed in version 3.10:Removed theloop parameter.
The preferred way to use a Semaphore is an
asyncwithstatement:sem=asyncio.Semaphore(10)# ... laterasyncwithsem:# work with shared resource
which is equivalent to:
sem=asyncio.Semaphore(10)# ... laterawaitsem.acquire()try:# work with shared resourcefinally:sem.release()
- asyncacquire()¶
Acquire a semaphore.
If the internal counter is greater than zero, decrementit by one and return
Trueimmediately. If it is zero, waituntil arelease()is called and returnTrue.
- locked()¶
Returns
Trueif semaphore can not be acquired immediately.
- release()¶
Release a semaphore, incrementing the internal counter by one.Can wake up a task waiting to acquire the semaphore.
Unlike
BoundedSemaphore,Semaphoreallowsmaking morerelease()calls thanacquire()calls.
BoundedSemaphore¶
- classasyncio.BoundedSemaphore(value=1)¶
A bounded semaphore object. Not thread-safe.
Bounded Semaphore is a version of
Semaphorethat raisesaValueErrorinrelease()if itincreases the internal counter above the initialvalue.Changed in version 3.10:Removed theloop parameter.
Barrier¶
- classasyncio.Barrier(parties)¶
A barrier object. Not thread-safe.
A barrier is a simple synchronization primitive that allows to block untilparties number of tasks are waiting on it.Tasks can wait on the
wait()method and would be blocked untilthe specified number of tasks end up waiting onwait().At that point all of the waiting tasks would unblock simultaneously.asyncwithcan be used as an alternative to awaiting onwait().The barrier can be reused any number of times.
Example:
asyncdefexample_barrier():# barrier with 3 partiesb=asyncio.Barrier(3)# create 2 new waiting tasksasyncio.create_task(b.wait())asyncio.create_task(b.wait())awaitasyncio.sleep(0)print(b)# The third .wait() call passes the barrierawaitb.wait()print(b)print("barrier passed")awaitasyncio.sleep(0)print(b)asyncio.run(example_barrier())
Result of this example is:
<asyncio.locks.Barrierobjectat0x...[filling,waiters:2/3]><asyncio.locks.Barrierobjectat0x...[draining,waiters:0/3]>barrierpassed<asyncio.locks.Barrierobjectat0x...[filling,waiters:0/3]>
Added in version 3.11.
- asyncwait()¶
Pass the barrier. When all the tasks party to the barrier have calledthis function, they are all unblocked simultaneously.
When a waiting or blocked task in the barrier is cancelled,this task exits the barrier which stays in the same state.If the state of the barrier is “filling”, the number of waiting taskdecreases by 1.
The return value is an integer in the range of 0 to
parties-1, differentfor each task. This can be used to select a task to do some specialhousekeeping, e.g.:...asyncwithbarrierasposition:ifposition==0:# Only one task prints thisprint('End of *draining phase*')
This method may raise a
BrokenBarrierErrorexception if thebarrier is broken or reset while a task is waiting.It could raise aCancelledErrorif a task is cancelled.
- asyncreset()¶
Return the barrier to the default, empty state. Any tasks waiting on itwill receive the
BrokenBarrierErrorexception.If a barrier is broken it may be better to just leave it and create a new one.
- asyncabort()¶
Put the barrier into a broken state. This causes any active or futurecalls to
wait()to fail with theBrokenBarrierError.Use this for example if one of the tasks needs to abort, to avoid infinitewaiting tasks.
- parties¶
The number of tasks required to pass the barrier.
- n_waiting¶
The number of tasks currently waiting in the barrier while filling.
- broken¶
A boolean that is
Trueif the barrier is in the broken state.
- exceptionasyncio.BrokenBarrierError¶
This exception, a subclass of
RuntimeError, is raised when theBarrierobject is reset or broken.
Changed in version 3.9:Acquiring a lock usingawaitlock oryieldfromlock and/orwith statement (withawaitlock,with(yieldfromlock)) was removed. Useasyncwithlock instead.