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 (usethreading forthat);

  • methods of these synchronization primitives do not accept thetimeoutargument; use theasyncio.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 anasyncwithstatement:

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 returnsTrue.

When more than one coroutine is blocked inacquire()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, aRuntimeError is raised.

locked()

ReturnTrue if 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 theset() 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, returnTrue immediately.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.

Tasks awaiting onwait() will now block until theset() method is called again.

is_set()

ReturnTrue if 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 anEvent and 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 aLock object 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 anasyncwithstatement:

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 returnsTrue.

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 lockaRuntimeError error is raised.

locked()

ReturnTrue if the underlying lock is acquired.

notify_all()

Wake up all tasks waiting on this condition.

This method acts likenotify(), but wakes up all waitingtasks.

The lock must be acquired before this method is called andreleased shortly after. If called with anunlocked lockaRuntimeError error is raised.

release()

Release the underlying lock.

When invoked on an unlocked lock, aRuntimeError israised.

asyncwait()

Wait until notified.

If the calling task has not acquired the lock when this method iscalled, aRuntimeError is raised.

This method releases the underlying lock, and then blocks untilit is awakened by anotify() 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 towait() again. For this reason, you mayprefer to usewait_for() instead.

asyncwait_for(predicate)

Wait until a predicate becomestrue.

The predicate must be a callable which result will beinterpreted as a boolean value. The method will repeatedlywait() until the predicate evaluates totrue. The final value is thereturn value.

Semaphore

classasyncio.Semaphore(value=1)

A Semaphore object. Not thread-safe.

A semaphore manages an internal counter which is decremented by eachacquire() 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 (1 by default). If the given value isless than0 aValueError is raised.

Changed in version 3.10:Removed theloop parameter.

The preferred way to use a Semaphore is anasyncwithstatement:

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 returnTrue immediately. If it is zero, waituntil arelease() is called and returnTrue.

locked()

ReturnsTrue if 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.

UnlikeBoundedSemaphore,Semaphore allowsmaking morerelease() calls thanacquire() calls.

BoundedSemaphore

classasyncio.BoundedSemaphore(value=1)

A bounded semaphore object. Not thread-safe.

Bounded Semaphore is a version ofSemaphore that raisesaValueError inrelease() 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 thewait() 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.

asyncwith can 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 toparties-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 aBrokenBarrierError exception if thebarrier is broken or reset while a task is waiting.It could raise aCancelledError if a task is cancelled.

asyncreset()

Return the barrier to the default, empty state. Any tasks waiting on itwill receive theBrokenBarrierError exception.

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 towait() 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 isTrue if the barrier is in the broken state.

exceptionasyncio.BrokenBarrierError

This exception, a subclass ofRuntimeError, is raised when theBarrier object is reset or broken.


Changed in version 3.9:Acquiring a lock usingawaitlock oryieldfromlock and/orwith statement (withawaitlock,with(yieldfromlock)) was removed. Useasyncwithlock instead.