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(*,loop=None)

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()

Deprecated since version 3.8, will be removed in version 3.10:Theloop parameter.

coroutineacquire()

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(*,loop=None)

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.

Deprecated since version 3.8, will be removed in version 3.10: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())
coroutinewait()

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,*,loop=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.

Deprecated since version 3.8, will be removed in version 3.10: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()
coroutineacquire()

Acquire the underlying lock.

This method waits until the underlying lock isunlocked,sets it tolocked and returnsTrue.

notify(n=1)

Wake up at mostn tasks (1 by default) waiting on thiscondition. The method is no-op if no tasks are waiting.

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.

coroutinewait()

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.

coroutinewait_for(predicate)

Wait until a predicate becomestrue.

The predicate must be a callable which result will beinterpreted as a boolean value. The final value is thereturn value.

Semaphore

classasyncio.Semaphore(value=1,*,loop=None)

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.

Deprecated since version 3.8, will be removed in version 3.10: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()
coroutineacquire()

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,*,loop=None)

A bounded semaphore object. Not thread-safe.

Bounded Semaphore is a version ofSemaphore that raisesaValueError inrelease() if itincreases the internal counter above the initialvalue.

Deprecated since version 3.8, will be removed in version 3.10:Theloop parameter.


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