Synchronization Primitives

Python documentation

Source code:

Lib/asyncio/locks.py

———
asyncio synchronization primitives are designed to be similar to those of the

threading

module with two important caveats:

asyncio primitives are not thread-safe, therefore they should not be used for OS thread synchronization (use

threading

for that);

methods of these synchronization primitives do not accept the timeout argument; use the

asyncio.wait_for()

function to perform operations with timeouts.

asyncio has the following basic synchronization primitives:

Lock

Event

Condition

Semaphore

BoundedSemaphore

Barrier

———
Lock

classasyncio.Lock

Implements a mutex lock for asyncio tasks. Not thread-safe.

An asyncio lock can be used to guarantee exclusive access to a shared resource.

The preferred way to use a Lock is an

async with

statement:

lock=asyncio.Lock()# ... laterasyncwithlock:# access shared statewhich is equivalent to:

lock=asyncio.Lock()# ... laterawaitlock.acquire()try:# access shared statefinally:lock.release()Changed in version 3.10: Removed the loop parameter.

asyncacquire()

Acquire the lock.

This method waits until the lock is unlocked, sets it to locked and returns True.

When more than one coroutine is blocked in acquire() waiting for the lock to be unlocked, only one coroutine eventually proceeds.

Acquiring a lock is fair: the coroutine that proceeds will be the first coroutine that started waiting on the lock.

release()

Release the lock.

When the lock is locked, reset it to unlocked and return.

If the lock is unlocked, a

RuntimeError

is raised.

locked()

Return True if the lock is locked.

Event

classasyncio.Event

An event object. Not thread-safe.

An asyncio event can be used to notify multiple asyncio tasks that some event has happened.

An Event object manages an internal flag that can be set to true with the

set()

method and reset to false with the

clear()

method. The

wait()

method blocks until the flag is set to true. The flag is set to false initially.

Changed in version 3.10: Removed the loop 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 True immediately. Otherwise block until another task calls

set()

.

set()

Set the event.

All tasks waiting for event to be set will be immediately awakened.

clear()

Clear (unset) the event.

Subsequent tasks awaiting on

wait()

will now block until the

set()

method is called again.

is_set()

Return True 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 for some event to happen and then get exclusive access to a shared resource.

In essence, a Condition object combines the functionality of an

Event

and a

Lock

. It is possible to have multiple Condition objects share one Lock, which allows coordinating exclusive access to a shared resource between different tasks interested in particular states of that shared resource.

The optional lock argument must be a

Lock

object or None. In the latter case a new Lock object is created automatically.

Changed in version 3.10: Removed the loop parameter.

The preferred way to use a Condition is an

async with

statement:

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 is unlocked, sets it to locked and returns True.

notify(n=1)

Wake up n tasks (1 by default) waiting on this condition. If fewer than n tasks are waiting they are all awakened.

The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a

RuntimeError

error is raised.

locked()

Return True if the underlying lock is acquired.

notify_all()

Wake up all tasks waiting on this condition.

This method acts like

notify()

, but wakes up all waiting tasks.

The lock must be acquired before this method is called and released shortly after. If called with an unlocked lock a

RuntimeError

error is raised.

release()

Release the underlying lock.

When invoked on an unlocked lock, a

RuntimeError

is raised.

asyncwait()

Wait until notified.

If the calling task has not acquired the lock when this method is called, a

RuntimeError

is raised.

This method releases the underlying lock, and then blocks until it is awakened by a

notify()

or

notify_all()

call. Once awakened, the Condition re-acquires its lock and this method returns True.

Note that a task may return from this call spuriously, which is why the caller should always re-check the state and be prepared to wait() again. For this reason, you may prefer to use

wait_for()

instead.

asyncwait_for(predicate)

Wait until a predicate becomes true.

The predicate must be a callable which result will be interpreted as a boolean value. The method will repeatedly

wait()

until the predicate evaluates to true. The final value is the return value.

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 each

release()

call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some task calls release().

The optional value argument gives the initial value for the internal counter (1 by default). If the given value is less than 0 a

ValueError

is raised.

Changed in version 3.10: Removed the loop parameter.

The preferred way to use a Semaphore is an

async with

statement:

sem=asyncio.Semaphore(10)# ... laterasyncwithsem:# work with shared resourcewhich 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, decrement it by one and return True immediately. If it is zero, wait until a

release()

is called and return True.

locked()

Returns True 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.

Unlike

BoundedSemaphore

, Semaphore allows making more release() calls than acquire() calls.

BoundedSemaphore

classasyncio.BoundedSemaphore(value=1)

A bounded semaphore object. Not thread-safe.

Bounded Semaphore is a version of

Semaphore

that raises a

ValueError

in

release()

if it increases the internal counter above the initial value.

Changed in version 3.10: Removed the loop parameter.

Barrier

classasyncio.Barrier(parties)

A barrier object. Not thread-safe.

A barrier is a simple synchronization primitive that allows to block until parties number of tasks are waiting on it. Tasks can wait on the

wait()

method and would be blocked until the specified number of tasks end up waiting on wait(). At that point all of the waiting tasks would unblock simultaneously.

async with

can be used as an alternative to awaiting on

wait()

.

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 called this 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 task decreases by 1.

The return value is an integer in the range of 0 to parties-1, different for each task. This can be used to select a task to do some special housekeeping, e.g.:

...asyncwithbarrierasposition:ifposition==0:# Only one task prints thisprint('End of *draining phase*')This method may raise a

BrokenBarrierError

exception if the barrier is broken or reset while a task is waiting. It could raise a

CancelledError

if a task is cancelled.

asyncreset()

Return the barrier to the default, empty state. Any tasks waiting on it will receive the

BrokenBarrierError

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 future calls to

wait()

to fail with the

BrokenBarrierError

. Use this for example if one of the tasks needs to abort, to avoid infinite waiting 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 True if the barrier is in the broken state.

exceptionasyncio.BrokenBarrierError

This exception, a subclass of

RuntimeError

, is raised when the

Barrier

object is reset or broken.

———
Changed in version 3.9: Acquiring a lock using awaitlock or yieldfromlock and/or

with

statement (withawaitlock, with(yieldfromlock)) was removed. Use asyncwithlock instead.