18.5.7.Synchronization primitives

Source code:Lib/asyncio/locks.py

Locks:

Semaphores:

asyncio lock API was designed to be close to classes of thethreadingmodule (Lock,Event,Condition,Semaphore,BoundedSemaphore), but it has notimeout parameter. Theasyncio.wait_for() function can be used to cancel a task after a timeout.

18.5.7.1.Locks

18.5.7.1.1.Lock

classasyncio.Lock(*,loop=None)

Primitive lock objects.

A primitive lock is a synchronization primitive that is not owned by aparticular coroutine when locked. A primitive lock is in one of two states,‘locked’ or ‘unlocked’.

It is created in the unlocked state. It has two basic methods,acquire()andrelease(). When the state is unlocked, acquire() changes the state tolocked and returns immediately. When the state is locked, acquire() blocksuntil a call to release() in another coroutine changes it to unlocked, thenthe acquire() call resets it to locked and returns. The release() methodshould only be called in the locked state; it changes the state to unlockedand returns immediately. If an attempt is made to release an unlocked lock,aRuntimeError will be raised.

When more than one coroutine is blocked in acquire() waiting for the stateto turn to unlocked, only one coroutine proceeds when a release() callresets the state to unlocked; first coroutine which is blocked in acquire()is being processed.

acquire() is a coroutine and should be called withyieldfrom.

Locks also support the context management protocol.(yieldfromlock)should be used as the context manager expression.

This class isnot thread safe.

Usage:

lock=Lock()...yield fromlocktry:...finally:lock.release()

Context manager usage:

lock=Lock()...with(yield fromlock):...

Lock objects can be tested for locking state:

ifnotlock.locked():yield fromlockelse:# lock is acquired...
locked()

ReturnTrue if the lock is acquired.

coroutineacquire()

Acquire a lock.

This method blocks until the lock is unlocked, then sets it to locked andreturnsTrue.

This method is acoroutine.

release()

Release a lock.

When the lock is locked, reset it to unlocked, and return. If any othercoroutines are blocked waiting for the lock to become unlocked, allowexactly one of them to proceed.

When invoked on an unlocked lock, aRuntimeError is raised.

There is no return value.

18.5.7.1.2.Event

classasyncio.Event(*,loop=None)

An Event implementation, asynchronous equivalent tothreading.Event.

Class implementing event objects. An event manages a flag that can be set totrue with theset() method and reset to false with theclear()method. Thewait() method blocks until the flag is true. The flag isinitially false.

This class isnot thread safe.

clear()

Reset the internal flag to false. Subsequently, coroutines callingwait() will block untilset() is called to set the internalflag to true again.

is_set()

ReturnTrue if and only if the internal flag is true.

set()

Set the internal flag to true. All coroutines waiting for it to becometrue are awakened. Coroutine that callwait() once the flag is truewill not block at all.

coroutinewait()

Block until the internal flag is true.

If the internal flag is true on entry, returnTrue immediately.Otherwise, block until another coroutine callsset() to set theflag to true, then returnTrue.

This method is acoroutine.

18.5.7.1.3.Condition

classasyncio.Condition(lock=None,*,loop=None)

A Condition implementation, asynchronous equivalent tothreading.Condition.

This class implements condition variable objects. A condition variableallows one or more coroutines to wait until they are notified by anothercoroutine.

If thelock argument is given and notNone, it must be aLockobject, and it is used as the underlying lock. Otherwise,a newLock object is created and used as the underlying lock.

This class isnot thread safe.

coroutineacquire()

Acquire the underlying lock.

This method blocks until the lock is unlocked, then sets it to locked andreturnsTrue.

This method is acoroutine.

notify(n=1)

By default, wake up one coroutine waiting on this condition, if any.If the calling coroutine has not acquired the lock when this method iscalled, aRuntimeError is raised.

This method wakes up at mostn of the coroutines waiting for thecondition variable; it is a no-op if no coroutines are waiting.

Note

An awakened coroutine does not actually return from itswait()call until it can reacquire the lock. Sincenotify() does notrelease the lock, its caller should.

locked()

ReturnTrue if the underlying lock is acquired.

notify_all()

Wake up all coroutines waiting on this condition. This method acts likenotify(), but wakes up all waiting coroutines instead of one. If thecalling coroutine has not acquired the lock when this method is called, aRuntimeError is raised.

release()

Release the underlying lock.

When the lock is locked, reset it to unlocked, and return. If any othercoroutines are blocked waiting for the lock to become unlocked, allowexactly one of them to proceed.

When invoked on an unlocked lock, aRuntimeError is raised.

There is no return value.

coroutinewait()

Wait until notified.

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

This method releases the underlying lock, and then blocks until it isawakened by anotify() ornotify_all() call for the samecondition variable in another coroutine. Once awakened, it re-acquiresthe lock and returnsTrue.

This method is acoroutine.

coroutinewait_for(predicate)

Wait until a predicate becomes true.

The predicate should be a callable which result will be interpreted as aboolean value. The final predicate value is the return value.

This method is acoroutine.

18.5.7.2.Semaphores

18.5.7.2.1.Semaphore

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

A Semaphore implementation.

A semaphore manages an internal counter which is decremented by eachacquire() call and incremented by eachrelease() call. Thecounter can never go below zero; whenacquire() finds that it is zero,it blocks, waiting until some other coroutine callsrelease().

Semaphores also support the context management protocol.

The optional argument gives the initial value for the internal counter; itdefaults to1. If the value given is less than0,ValueErroris raised.

This class isnot thread safe.

coroutineacquire()

Acquire a semaphore.

If the internal counter is larger than zero on entry, decrement it by oneand returnTrue immediately. If it is zero on entry, block, waitinguntil some other coroutine has calledrelease() to make it largerthan0, and then returnTrue.

This method is acoroutine.

locked()

ReturnsTrue if semaphore can not be acquired immediately.

release()

Release a semaphore, incrementing the internal counter by one. When itwas zero on entry and another coroutine is waiting for it to becomelarger than zero again, wake up that coroutine.

18.5.7.2.2.BoundedSemaphore

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

A bounded semaphore implementation. Inherit fromSemaphore.

This raisesValueError inrelease() if it wouldincrease the value above the initial value.