"""Synchronization primitives."""
__all__ = ['Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore']
from .coroutines import coroutine
This enables the following idiom for acquiring and releasing a
while failing loudly when accidentally using:
def __init__(self, lock):
# We have no use for the "as ..." clause in the with
def __exit__(self, *args):
self._lock = None # Crudely prevent reuse.
class _ContextManagerMixin:
'"yield from" should be used as context manager expression')
def __exit__(self, *args):
# This must exist because __enter__ exists, even though that
# always raises; that's how the with-statement works.
# This is not a coroutine. It is meant to enable the idiom:
# with (yield from lock):
# yield from lock.acquire()
yield from self.acquire()
return _ContextManager(self)
# To make "with await lock" work.
yield from self.acquire()
return _ContextManager(self)
yield from self.acquire()
# We have no use for the "as ..." clause in the with
def __aexit__(self, exc_type, exc, tb):
class Lock(_ContextManagerMixin):
"""Primitive lock objects.
A primitive lock is a synchronization primitive that is not owned
by a particular 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() and release(). When the state is unlocked, acquire()
changes the state to locked and returns immediately. When the
state is locked, acquire() blocks until a call to release() in
another coroutine changes it to unlocked, then the acquire() call
resets it to locked and returns. The release() method should only
be called in the locked state; it changes the state to unlocked
and returns immediately. If an attempt is made to release an
unlocked lock, a RuntimeError will be raised.
When more than one coroutine is blocked in acquire() waiting for
the state to turn to unlocked, only one coroutine proceeds when a
release() call resets the state to unlocked; first coroutine which
is blocked in acquire() is being processed.
acquire() is a coroutine and should be called with 'yield from'.
Locks also support the context management protocol. '(yield from lock)'
should be used as the context manager expression.
Lock objects can be tested for locking state:
def __init__(self, *, loop=None):
self._waiters = collections.deque()
self._loop = events.get_event_loop()
extra = 'locked' if self._locked else 'unlocked'
extra = '{},waiters:{}'.format(extra, len(self._waiters))
return '<{} [{}]>'.format(res[1:-1], extra)
"""Return True if lock is acquired."""
This method blocks until the lock is unlocked, then sets it to
if not self._locked and all(w.cancelled() for w in self._waiters):
fut = self._loop.create_future()
self._waiters.append(fut)
# Finally block should be called before the CancelledError
# handling as we don't want CancelledError to call
# _wake_up_first() and attempt to wake up itself.
self._waiters.remove(fut)
except futures.CancelledError:
When the lock is locked, reset it to unlocked, and return.
If any other coroutines are blocked waiting for the lock to become
unlocked, allow exactly one of them to proceed.
When invoked on an unlocked lock, a RuntimeError is raised.
There is no return value.
raise RuntimeError('Lock is not acquired.')
def _wake_up_first(self):
"""Wake up the first waiter if it isn't done."""
fut = next(iter(self._waiters))
# .done() necessarily means that a waiter will wake up later on and
# either take the lock, or, if it was cancelled and lock wasn't
# taken already, will hit this again and wake up a new waiter.
"""Asynchronous equivalent to threading.Event.
Class implementing event objects. An event manages a 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 true. The flag is initially
def __init__(self, *, loop=None):
self._waiters = collections.deque()
self._loop = events.get_event_loop()
extra = 'set' if self._value else 'unset'
extra = '{},waiters:{}'.format(extra, len(self._waiters))
return '<{} [{}]>'.format(res[1:-1], extra)
"""Return True if and only if the internal flag is true."""
"""Set the internal flag to true. All coroutines waiting for it to
become true are awakened. Coroutine that call wait() once the flag is
true will not block at all.
for fut in self._waiters:
"""Reset the internal flag to false. Subsequently, coroutines calling
wait() will block until set() is called to set the internal flag
"""Block until the internal flag is true.
If the internal flag is true on entry, return True
immediately. Otherwise, block until another coroutine calls
set() to set the flag to true, then return True.
fut = self._loop.create_future()
self._waiters.append(fut)
self._waiters.remove(fut)
class Condition(_ContextManagerMixin):
"""Asynchronous equivalent to threading.Condition.
This class implements condition variable objects. A condition variable
allows one or more coroutines to wait until they are notified by another
A new Lock object is created and used as the underlying lock.
def __init__(self, lock=None, *, loop=None):
self._loop = events.get_event_loop()
lock = Lock(loop=self._loop)
elif lock._loop is not self._loop:
raise ValueError("loop argument must agree with lock")
# Export the lock's locked(), acquire() and release() methods.
self.locked = lock.locked
self.acquire = lock.acquire
self.release = lock.release
self._waiters = collections.deque()
extra = 'locked' if self.locked() else 'unlocked'
extra = '{},waiters:{}'.format(extra, len(self._waiters))
return '<{} [{}]>'.format(res[1:-1], extra)
If the calling coroutine 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 for
the same condition variable in another coroutine. Once
awakened, it re-acquires the lock and returns True.
raise RuntimeError('cannot wait on un-acquired lock')
fut = self._loop.create_future()
self._waiters.append(fut)
self._waiters.remove(fut)
# Must reacquire lock even if wait is cancelled
yield from self.acquire()
except futures.CancelledError:
raise futures.CancelledError
def wait_for(self, predicate):
"""Wait until a predicate becomes true.
The predicate should be a callable which result will be
interpreted as a boolean value. The final predicate value is
"""By default, wake up one coroutine waiting on this condition, if any.
If the calling coroutine has not acquired the lock when this method
is called, a RuntimeError is raised.
This method wakes up at most n of the coroutines waiting for the
condition variable; it is a no-op if no coroutines are waiting.
Note: an awakened coroutine does not actually return from its
wait() call until it can reacquire the lock. Since notify() does
not release the lock, its caller should.
raise RuntimeError('cannot notify on un-acquired lock')
for fut in self._waiters:
"""Wake up all threads waiting on this condition. This method acts
like notify(), but wakes up all waiting threads instead of one. If the
calling thread has not acquired the lock when this method is called,
a RuntimeError is raised.
self.notify(len(self._waiters))
class Semaphore(_ContextManagerMixin):
"""A Semaphore implementation.
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 other thread calls release().
Semaphores also support the context management protocol.
The optional argument gives the initial value for the internal
counter; it defaults to 1. If the value given is less than 0,
def __init__(self, value=1, *, loop=None):
raise ValueError("Semaphore initial value must be >= 0")
self._waiters = collections.deque()
self._loop = events.get_event_loop()
extra = 'locked' if self.locked() else 'unlocked,value:{}'.format(
extra = '{},waiters:{}'.format(extra, len(self._waiters))
return '<{} [{}]>'.format(res[1:-1], extra)
waiter = self._waiters.popleft()
"""Returns True if semaphore can not be acquired immediately."""
If the internal counter is larger than zero on entry,
decrement it by one and return True immediately. If it is
zero on entry, block, waiting until some other coroutine has
called release() to make it larger than 0, and then return
fut = self._loop.create_future()
self._waiters.append(fut)
# See the similar code in Queue.get.
if self._value > 0 and not fut.cancelled():
"""Release a semaphore, incrementing the internal counter by one.
When it was zero on entry and another coroutine is waiting for it to
become larger than zero again, wake up that coroutine.
class BoundedSemaphore(Semaphore):
"""A bounded semaphore implementation.
This raises ValueError in release() if it would increase the value
def __init__(self, value=1, *, loop=None):
self._bound_value = value
super().__init__(value, loop=loop)
if self._value >= self._bound_value:
raise ValueError('BoundedSemaphore released too many times')