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¶
- class
asyncio.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 an
asyncwithstatement: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.
- coroutine
acquire()¶ 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.
- coroutine
Event¶
- class
asyncio.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 the
set()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())
- coroutine
wait()¶ 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.
Tasks awaiting on
wait()will now block until theset()method is called again.
is_set()¶Return
Trueif the event is set.
- coroutine
Condition¶
- class
asyncio.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 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.Deprecated since version 3.8, will be removed in version 3.10: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()
- coroutine
acquire()¶ Acquire the underlying lock.
This method waits until the underlying lock isunlocked,sets it tolocked and returns
True.
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 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.
- coroutine
wait()¶ 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.
- coroutine
wait_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.
- coroutine
Semaphore¶
- class
asyncio.Semaphore(value=1,*,loop=None)¶ 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.Deprecated since version 3.8, will be removed in version 3.10: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()
- coroutine
acquire()¶ 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.
- coroutine
BoundedSemaphore¶
- class
asyncio.BoundedSemaphore(value=1,*,loop=None)¶ A bounded semaphore object. Not thread-safe.
Bounded Semaphore is a version of
Semaphorethat raisesaValueErrorinrelease()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.