2013-10-17 17:40:50 -03:00
|
|
|
"""Synchronization primitives."""
|
|
|
|
|
2022-03-25 19:01:21 -03:00
|
|
|
__all__ = ('Lock', 'Event', 'Condition', 'Semaphore',
|
|
|
|
'BoundedSemaphore', 'Barrier')
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
import collections
|
2022-03-25 19:01:21 -03:00
|
|
|
import enum
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2018-09-11 14:13:04 -03:00
|
|
|
from . import exceptions
|
2020-11-24 14:08:54 -04:00
|
|
|
from . import mixins
|
2014-01-25 20:51:57 -04:00
|
|
|
|
2015-05-13 16:15:56 -03:00
|
|
|
class _ContextManagerMixin:
|
2017-12-08 18:23:48 -04:00
|
|
|
async def __aenter__(self):
|
|
|
|
await self.acquire()
|
2017-11-28 09:43:52 -04:00
|
|
|
# We have no use for the "as ..." clause in the with
|
|
|
|
# statement for locks.
|
|
|
|
return None
|
2015-05-13 16:15:56 -03:00
|
|
|
|
2017-12-08 18:23:48 -04:00
|
|
|
async def __aexit__(self, exc_type, exc, tb):
|
2017-11-28 09:43:52 -04:00
|
|
|
self.release()
|
2015-05-13 16:15:56 -03:00
|
|
|
|
|
|
|
|
2020-11-25 07:50:44 -04:00
|
|
|
class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
|
2013-10-17 17:40:50 -03:00
|
|
|
"""Primitive lock objects.
|
|
|
|
|
|
|
|
A primitive lock is a synchronization primitive that is not owned
|
2024-02-03 12:19:37 -04:00
|
|
|
by a particular task when locked. A primitive lock is in one
|
2013-10-17 17:40:50 -03:00
|
|
|
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
|
2024-02-03 12:19:37 -04:00
|
|
|
another task changes it to unlocked, then the acquire() call
|
2013-10-17 17:40:50 -03:00
|
|
|
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.
|
|
|
|
|
2024-02-03 12:19:37 -04:00
|
|
|
When more than one task is blocked in acquire() waiting for
|
|
|
|
the state to turn to unlocked, only one task proceeds when a
|
|
|
|
release() call resets the state to unlocked; successive release()
|
|
|
|
calls will unblock tasks in FIFO order.
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2017-12-11 11:35:49 -04:00
|
|
|
Locks also support the asynchronous context management protocol.
|
|
|
|
'async with lock' statement should be used.
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
Usage:
|
|
|
|
|
|
|
|
lock = Lock()
|
|
|
|
...
|
2017-12-11 11:35:49 -04:00
|
|
|
await lock.acquire()
|
2013-10-17 17:40:50 -03:00
|
|
|
try:
|
|
|
|
...
|
|
|
|
finally:
|
|
|
|
lock.release()
|
|
|
|
|
|
|
|
Context manager usage:
|
|
|
|
|
|
|
|
lock = Lock()
|
|
|
|
...
|
2017-12-11 11:35:49 -04:00
|
|
|
async with lock:
|
2013-10-17 17:40:50 -03:00
|
|
|
...
|
|
|
|
|
|
|
|
Lock objects can be tested for locking state:
|
|
|
|
|
|
|
|
if not lock.locked():
|
2017-12-11 11:35:49 -04:00
|
|
|
await lock.acquire()
|
2013-10-17 17:40:50 -03:00
|
|
|
else:
|
|
|
|
# lock is acquired
|
|
|
|
...
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
2022-02-21 07:25:52 -04:00
|
|
|
def __init__(self):
|
2019-06-05 06:33:27 -03:00
|
|
|
self._waiters = None
|
2013-10-17 17:40:50 -03:00
|
|
|
self._locked = False
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
res = super().__repr__()
|
|
|
|
extra = 'locked' if self._locked else 'unlocked'
|
|
|
|
if self._waiters:
|
2017-12-10 19:36:12 -04:00
|
|
|
extra = f'{extra}, waiters:{len(self._waiters)}'
|
|
|
|
return f'<{res[1:-1]} [{extra}]>'
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
def locked(self):
|
2013-12-02 09:31:16 -04:00
|
|
|
"""Return True if lock is acquired."""
|
2013-10-17 17:40:50 -03:00
|
|
|
return self._locked
|
|
|
|
|
2017-12-08 18:23:48 -04:00
|
|
|
async def acquire(self):
|
2013-10-17 17:40:50 -03:00
|
|
|
"""Acquire a lock.
|
|
|
|
|
|
|
|
This method blocks until the lock is unlocked, then sets it to
|
|
|
|
locked and returns True.
|
|
|
|
"""
|
2024-01-08 15:57:48 -04:00
|
|
|
# Implement fair scheduling, where thread always waits
|
|
|
|
# its turn. Jumping the queue if all are cancelled is an optimization.
|
2019-06-05 06:33:27 -03:00
|
|
|
if (not self._locked and (self._waiters is None or
|
|
|
|
all(w.cancelled() for w in self._waiters))):
|
2013-10-17 17:40:50 -03:00
|
|
|
self._locked = True
|
|
|
|
return True
|
|
|
|
|
2019-06-05 06:33:27 -03:00
|
|
|
if self._waiters is None:
|
|
|
|
self._waiters = collections.deque()
|
2020-11-24 14:08:54 -04:00
|
|
|
fut = self._get_loop().create_future()
|
2013-10-17 17:40:50 -03:00
|
|
|
self._waiters.append(fut)
|
2018-02-02 18:04:00 -04:00
|
|
|
|
2013-10-17 17:40:50 -03:00
|
|
|
try:
|
2018-02-02 18:04:00 -04:00
|
|
|
try:
|
|
|
|
await fut
|
|
|
|
finally:
|
|
|
|
self._waiters.remove(fut)
|
2018-09-11 14:13:04 -03:00
|
|
|
except exceptions.CancelledError:
|
2024-01-08 15:57:48 -04:00
|
|
|
# Currently the only exception designed be able to occur here.
|
|
|
|
|
|
|
|
# Ensure the lock invariant: If lock is not claimed (or about
|
|
|
|
# to be claimed by us) and there is a Task in waiters,
|
|
|
|
# ensure that the Task at the head will run.
|
2017-06-09 17:17:40 -03:00
|
|
|
if not self._locked:
|
|
|
|
self._wake_up_first()
|
|
|
|
raise
|
2018-02-02 18:04:00 -04:00
|
|
|
|
2024-01-08 15:57:48 -04:00
|
|
|
# assert self._locked is False
|
2018-02-02 18:04:00 -04:00
|
|
|
self._locked = True
|
|
|
|
return True
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
def release(self):
|
|
|
|
"""Release a lock.
|
|
|
|
|
|
|
|
When the lock is locked, reset it to unlocked, and return.
|
2024-02-03 12:19:37 -04:00
|
|
|
If any other tasks are blocked waiting for the lock to become
|
2013-10-17 17:40:50 -03:00
|
|
|
unlocked, allow exactly one of them to proceed.
|
|
|
|
|
|
|
|
When invoked on an unlocked lock, a RuntimeError is raised.
|
|
|
|
|
|
|
|
There is no return value.
|
|
|
|
"""
|
|
|
|
if self._locked:
|
|
|
|
self._locked = False
|
2017-06-09 17:17:40 -03:00
|
|
|
self._wake_up_first()
|
2013-10-17 17:40:50 -03:00
|
|
|
else:
|
|
|
|
raise RuntimeError('Lock is not acquired.')
|
|
|
|
|
2017-06-09 17:17:40 -03:00
|
|
|
def _wake_up_first(self):
|
2024-01-08 15:57:48 -04:00
|
|
|
"""Ensure that the first waiter will wake up."""
|
2019-06-05 06:33:27 -03:00
|
|
|
if not self._waiters:
|
|
|
|
return
|
2018-02-02 18:04:00 -04:00
|
|
|
try:
|
|
|
|
fut = next(iter(self._waiters))
|
|
|
|
except StopIteration:
|
|
|
|
return
|
|
|
|
|
2024-01-08 15:57:48 -04:00
|
|
|
# .done() means that the waiter is already set to wake up.
|
2018-02-02 18:04:00 -04:00
|
|
|
if not fut.done():
|
|
|
|
fut.set_result(True)
|
2017-06-09 17:17:40 -03:00
|
|
|
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2020-11-25 07:50:44 -04:00
|
|
|
class Event(mixins._LoopBoundMixin):
|
2013-12-19 16:47:38 -04:00
|
|
|
"""Asynchronous equivalent to threading.Event.
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
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
|
|
|
|
false.
|
|
|
|
"""
|
|
|
|
|
2022-02-21 07:25:52 -04:00
|
|
|
def __init__(self):
|
2013-10-17 17:40:50 -03:00
|
|
|
self._waiters = collections.deque()
|
|
|
|
self._value = False
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
res = super().__repr__()
|
2013-11-04 17:18:19 -04:00
|
|
|
extra = 'set' if self._value else 'unset'
|
|
|
|
if self._waiters:
|
2017-12-10 19:36:12 -04:00
|
|
|
extra = f'{extra}, waiters:{len(self._waiters)}'
|
|
|
|
return f'<{res[1:-1]} [{extra}]>'
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
def is_set(self):
|
2013-12-02 09:31:16 -04:00
|
|
|
"""Return True if and only if the internal flag is true."""
|
2013-10-17 17:40:50 -03:00
|
|
|
return self._value
|
|
|
|
|
|
|
|
def set(self):
|
2024-02-03 12:19:37 -04:00
|
|
|
"""Set the internal flag to true. All tasks waiting for it to
|
|
|
|
become true are awakened. Tasks that call wait() once the flag is
|
2013-10-17 17:40:50 -03:00
|
|
|
true will not block at all.
|
|
|
|
"""
|
|
|
|
if not self._value:
|
|
|
|
self._value = True
|
|
|
|
|
|
|
|
for fut in self._waiters:
|
|
|
|
if not fut.done():
|
|
|
|
fut.set_result(True)
|
|
|
|
|
|
|
|
def clear(self):
|
2024-02-03 12:19:37 -04:00
|
|
|
"""Reset the internal flag to false. Subsequently, tasks calling
|
2013-10-17 17:40:50 -03:00
|
|
|
wait() will block until set() is called to set the internal flag
|
|
|
|
to true again."""
|
|
|
|
self._value = False
|
|
|
|
|
2017-12-08 18:23:48 -04:00
|
|
|
async def wait(self):
|
2013-10-17 17:40:50 -03:00
|
|
|
"""Block until the internal flag is true.
|
|
|
|
|
|
|
|
If the internal flag is true on entry, return True
|
2024-02-03 12:19:37 -04:00
|
|
|
immediately. Otherwise, block until another task calls
|
2013-10-17 17:40:50 -03:00
|
|
|
set() to set the flag to true, then return True.
|
|
|
|
"""
|
|
|
|
if self._value:
|
|
|
|
return True
|
|
|
|
|
2020-11-24 14:08:54 -04:00
|
|
|
fut = self._get_loop().create_future()
|
2013-10-17 17:40:50 -03:00
|
|
|
self._waiters.append(fut)
|
|
|
|
try:
|
2017-12-08 18:23:48 -04:00
|
|
|
await fut
|
2013-10-17 17:40:50 -03:00
|
|
|
return True
|
|
|
|
finally:
|
|
|
|
self._waiters.remove(fut)
|
|
|
|
|
|
|
|
|
2020-11-25 07:50:44 -04:00
|
|
|
class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
|
2013-12-19 16:47:38 -04:00
|
|
|
"""Asynchronous equivalent to threading.Condition.
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
This class implements condition variable objects. A condition variable
|
2024-02-03 12:19:37 -04:00
|
|
|
allows one or more tasks to wait until they are notified by another
|
|
|
|
task.
|
2013-11-04 17:18:19 -04:00
|
|
|
|
|
|
|
A new Lock object is created and used as the underlying lock.
|
2013-10-17 17:40:50 -03:00
|
|
|
"""
|
|
|
|
|
2022-02-21 07:25:52 -04:00
|
|
|
def __init__(self, lock=None):
|
2014-07-26 11:54:34 -03:00
|
|
|
if lock is None:
|
2020-11-24 14:08:54 -04:00
|
|
|
lock = Lock()
|
2014-07-26 11:54:34 -03:00
|
|
|
|
2013-11-04 17:18:19 -04:00
|
|
|
self._lock = 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()
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
res = super().__repr__()
|
|
|
|
extra = 'locked' if self.locked() else 'unlocked'
|
|
|
|
if self._waiters:
|
2017-12-10 19:36:12 -04:00
|
|
|
extra = f'{extra}, waiters:{len(self._waiters)}'
|
|
|
|
return f'<{res[1:-1]} [{extra}]>'
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2017-12-08 18:23:48 -04:00
|
|
|
async def wait(self):
|
2013-10-17 17:40:50 -03:00
|
|
|
"""Wait until notified.
|
|
|
|
|
2024-02-03 12:19:37 -04:00
|
|
|
If the calling task has not acquired the lock when this
|
2013-10-17 17:40:50 -03:00
|
|
|
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
|
2024-02-03 12:19:37 -04:00
|
|
|
the same condition variable in another task. Once
|
2013-10-17 17:40:50 -03:00
|
|
|
awakened, it re-acquires the lock and returns True.
|
2024-02-03 12:19:37 -04:00
|
|
|
|
|
|
|
This method may return spuriously,
|
|
|
|
which is why the caller should always
|
|
|
|
re-check the state and be prepared to wait() again.
|
2013-10-17 17:40:50 -03:00
|
|
|
"""
|
2013-11-04 17:18:19 -04:00
|
|
|
if not self.locked():
|
2013-10-17 17:40:50 -03:00
|
|
|
raise RuntimeError('cannot wait on un-acquired lock')
|
|
|
|
|
2024-02-03 12:19:37 -04:00
|
|
|
fut = self._get_loop().create_future()
|
2013-10-17 17:40:50 -03:00
|
|
|
self.release()
|
|
|
|
try:
|
|
|
|
try:
|
2024-02-03 12:19:37 -04:00
|
|
|
self._waiters.append(fut)
|
2024-01-08 15:57:48 -04:00
|
|
|
try:
|
2024-02-03 12:19:37 -04:00
|
|
|
await fut
|
|
|
|
return True
|
2024-01-08 15:57:48 -04:00
|
|
|
finally:
|
2024-02-03 12:19:37 -04:00
|
|
|
self._waiters.remove(fut)
|
|
|
|
|
|
|
|
finally:
|
|
|
|
# Must re-acquire lock even if wait is cancelled.
|
|
|
|
# We only catch CancelledError here, since we don't want any
|
|
|
|
# other (fatal) errors with the future to cause us to spin.
|
|
|
|
err = None
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
await self.acquire()
|
|
|
|
break
|
|
|
|
except exceptions.CancelledError as e:
|
|
|
|
err = e
|
|
|
|
|
|
|
|
if err is not None:
|
|
|
|
try:
|
|
|
|
raise err # Re-raise most recent exception instance.
|
|
|
|
finally:
|
|
|
|
err = None # Break reference cycles.
|
|
|
|
except BaseException:
|
|
|
|
# Any error raised out of here _may_ have occurred after this Task
|
|
|
|
# believed to have been successfully notified.
|
|
|
|
# Make sure to notify another Task instead. This may result
|
|
|
|
# in a "spurious wakeup", which is allowed as part of the
|
|
|
|
# Condition Variable protocol.
|
|
|
|
self._notify(1)
|
|
|
|
raise
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2017-12-08 18:23:48 -04:00
|
|
|
async def wait_for(self, predicate):
|
2013-10-17 17:40:50 -03:00
|
|
|
"""Wait until a predicate becomes true.
|
|
|
|
|
2024-02-03 12:19:37 -04:00
|
|
|
The predicate should be a callable whose result will be
|
|
|
|
interpreted as a boolean value. The method will repeatedly
|
|
|
|
wait() until it evaluates to true. The final predicate value is
|
2013-10-17 17:40:50 -03:00
|
|
|
the return value.
|
|
|
|
"""
|
|
|
|
result = predicate()
|
|
|
|
while not result:
|
2017-12-08 18:23:48 -04:00
|
|
|
await self.wait()
|
2013-10-17 17:40:50 -03:00
|
|
|
result = predicate()
|
|
|
|
return result
|
|
|
|
|
|
|
|
def notify(self, n=1):
|
2024-02-03 12:19:37 -04:00
|
|
|
"""By default, wake up one task waiting on this condition, if any.
|
|
|
|
If the calling task has not acquired the lock when this method
|
2013-10-17 17:40:50 -03:00
|
|
|
is called, a RuntimeError is raised.
|
|
|
|
|
2024-02-03 12:19:37 -04:00
|
|
|
This method wakes up n of the tasks waiting for the condition
|
|
|
|
variable; if fewer than n are waiting, they are all awoken.
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2024-02-03 12:19:37 -04:00
|
|
|
Note: an awakened task does not actually return from its
|
2013-10-17 17:40:50 -03:00
|
|
|
wait() call until it can reacquire the lock. Since notify() does
|
|
|
|
not release the lock, its caller should.
|
|
|
|
"""
|
2013-11-04 17:18:19 -04:00
|
|
|
if not self.locked():
|
2013-10-17 17:40:50 -03:00
|
|
|
raise RuntimeError('cannot notify on un-acquired lock')
|
2024-02-03 12:19:37 -04:00
|
|
|
self._notify(n)
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2024-02-03 12:19:37 -04:00
|
|
|
def _notify(self, n):
|
2013-10-17 17:40:50 -03:00
|
|
|
idx = 0
|
2013-11-04 17:18:19 -04:00
|
|
|
for fut in self._waiters:
|
2013-10-17 17:40:50 -03:00
|
|
|
if idx >= n:
|
|
|
|
break
|
|
|
|
|
|
|
|
if not fut.done():
|
|
|
|
idx += 1
|
|
|
|
fut.set_result(False)
|
|
|
|
|
|
|
|
def notify_all(self):
|
|
|
|
"""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.
|
|
|
|
"""
|
2013-11-04 17:18:19 -04:00
|
|
|
self.notify(len(self._waiters))
|
|
|
|
|
|
|
|
|
2020-11-25 07:50:44 -04:00
|
|
|
class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
|
2013-10-17 17:40:50 -03:00
|
|
|
"""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().
|
|
|
|
|
2014-09-10 17:43:41 -03:00
|
|
|
Semaphores also support the context management protocol.
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2013-11-23 19:09:16 -04:00
|
|
|
The optional argument gives the initial value for the internal
|
2013-10-17 17:40:50 -03:00
|
|
|
counter; it defaults to 1. If the value given is less than 0,
|
|
|
|
ValueError is raised.
|
|
|
|
"""
|
|
|
|
|
2022-02-21 07:25:52 -04:00
|
|
|
def __init__(self, value=1):
|
2013-10-17 17:40:50 -03:00
|
|
|
if value < 0:
|
2013-11-21 15:07:45 -04:00
|
|
|
raise ValueError("Semaphore initial value must be >= 0")
|
2022-09-22 13:34:45 -03:00
|
|
|
self._waiters = None
|
2013-10-17 17:40:50 -03:00
|
|
|
self._value = value
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
res = super().__repr__()
|
2017-12-10 19:36:12 -04:00
|
|
|
extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
|
2013-11-04 17:18:19 -04:00
|
|
|
if self._waiters:
|
2017-12-10 19:36:12 -04:00
|
|
|
extra = f'{extra}, waiters:{len(self._waiters)}'
|
|
|
|
return f'<{res[1:-1]} [{extra}]>'
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
def locked(self):
|
2022-09-26 20:38:00 -03:00
|
|
|
"""Returns True if semaphore cannot be acquired immediately."""
|
2024-01-08 15:57:48 -04:00
|
|
|
# Due to state, or FIFO rules (must allow others to run first).
|
2022-09-26 20:38:00 -03:00
|
|
|
return self._value == 0 or (
|
|
|
|
any(not w.cancelled() for w in (self._waiters or ())))
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2017-12-08 18:23:48 -04:00
|
|
|
async def acquire(self):
|
2013-10-17 17:40:50 -03:00
|
|
|
"""Acquire a semaphore.
|
|
|
|
|
|
|
|
If the internal counter is larger than zero on entry,
|
|
|
|
decrement it by one and return True immediately. If it is
|
2024-02-03 12:19:37 -04:00
|
|
|
zero on entry, block, waiting until some other task has
|
2013-10-17 17:40:50 -03:00
|
|
|
called release() to make it larger than 0, and then return
|
|
|
|
True.
|
|
|
|
"""
|
2022-09-26 20:38:00 -03:00
|
|
|
if not self.locked():
|
2024-01-08 15:57:48 -04:00
|
|
|
# Maintain FIFO, wait for others to start even if _value > 0.
|
2022-09-22 13:34:45 -03:00
|
|
|
self._value -= 1
|
|
|
|
return True
|
|
|
|
|
|
|
|
if self._waiters is None:
|
|
|
|
self._waiters = collections.deque()
|
|
|
|
fut = self._get_loop().create_future()
|
|
|
|
self._waiters.append(fut)
|
|
|
|
|
|
|
|
try:
|
2015-09-29 15:54:45 -03:00
|
|
|
try:
|
2017-12-08 18:23:48 -04:00
|
|
|
await fut
|
2022-09-22 13:34:45 -03:00
|
|
|
finally:
|
|
|
|
self._waiters.remove(fut)
|
|
|
|
except exceptions.CancelledError:
|
2024-01-08 15:57:48 -04:00
|
|
|
# Currently the only exception designed be able to occur here.
|
|
|
|
if fut.done() and not fut.cancelled():
|
|
|
|
# Our Future was successfully set to True via _wake_up_next(),
|
|
|
|
# but we are not about to successfully acquire(). Therefore we
|
|
|
|
# must undo the bookkeeping already done and attempt to wake
|
|
|
|
# up someone else.
|
2022-09-26 20:38:00 -03:00
|
|
|
self._value += 1
|
2022-09-22 13:34:45 -03:00
|
|
|
raise
|
|
|
|
|
2024-01-08 15:57:48 -04:00
|
|
|
finally:
|
|
|
|
# New waiters may have arrived but had to wait due to FIFO.
|
|
|
|
# Wake up as many as are allowed.
|
|
|
|
while self._value > 0:
|
|
|
|
if not self._wake_up_next():
|
|
|
|
break # There was no-one to wake up.
|
2015-09-29 15:54:45 -03:00
|
|
|
return True
|
2013-10-17 17:40:50 -03:00
|
|
|
|
|
|
|
def release(self):
|
|
|
|
"""Release a semaphore, incrementing the internal counter by one.
|
2022-09-22 13:34:45 -03:00
|
|
|
|
2024-02-03 12:19:37 -04:00
|
|
|
When it was zero on entry and another task is waiting for it to
|
|
|
|
become larger than zero again, wake up that task.
|
2013-10-17 17:40:50 -03:00
|
|
|
"""
|
|
|
|
self._value += 1
|
2022-09-26 20:38:00 -03:00
|
|
|
self._wake_up_next()
|
2022-09-22 13:34:45 -03:00
|
|
|
|
2022-09-26 20:38:00 -03:00
|
|
|
def _wake_up_next(self):
|
|
|
|
"""Wake up the first waiter that isn't done."""
|
2022-09-22 13:34:45 -03:00
|
|
|
if not self._waiters:
|
2024-01-08 15:57:48 -04:00
|
|
|
return False
|
2022-09-22 13:34:45 -03:00
|
|
|
|
2022-09-26 20:38:00 -03:00
|
|
|
for fut in self._waiters:
|
|
|
|
if not fut.done():
|
|
|
|
self._value -= 1
|
|
|
|
fut.set_result(True)
|
2024-01-08 15:57:48 -04:00
|
|
|
# `fut` is now `done()` and not `cancelled()`.
|
|
|
|
return True
|
|
|
|
return False
|
2013-10-17 17:40:50 -03:00
|
|
|
|
2013-11-23 19:09:16 -04:00
|
|
|
|
|
|
|
class BoundedSemaphore(Semaphore):
|
|
|
|
"""A bounded semaphore implementation.
|
|
|
|
|
|
|
|
This raises ValueError in release() if it would increase the value
|
|
|
|
above the initial value.
|
|
|
|
"""
|
|
|
|
|
2022-02-21 07:25:52 -04:00
|
|
|
def __init__(self, value=1):
|
2013-11-23 19:09:16 -04:00
|
|
|
self._bound_value = value
|
2022-02-21 07:25:52 -04:00
|
|
|
super().__init__(value)
|
2013-11-23 19:09:16 -04:00
|
|
|
|
|
|
|
def release(self):
|
|
|
|
if self._value >= self._bound_value:
|
|
|
|
raise ValueError('BoundedSemaphore released too many times')
|
|
|
|
super().release()
|
2022-03-25 19:01:21 -03:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class _BarrierState(enum.Enum):
|
|
|
|
FILLING = 'filling'
|
|
|
|
DRAINING = 'draining'
|
|
|
|
RESETTING = 'resetting'
|
|
|
|
BROKEN = 'broken'
|
|
|
|
|
|
|
|
|
|
|
|
class Barrier(mixins._LoopBoundMixin):
|
|
|
|
"""Asyncio equivalent to threading.Barrier
|
|
|
|
|
|
|
|
Implements a Barrier primitive.
|
|
|
|
Useful for synchronizing a fixed number of tasks at known synchronization
|
|
|
|
points. Tasks block on 'wait()' and are simultaneously awoken once they
|
|
|
|
have all made their call.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, parties):
|
|
|
|
"""Create a barrier, initialised to 'parties' tasks."""
|
|
|
|
if parties < 1:
|
|
|
|
raise ValueError('parties must be > 0')
|
|
|
|
|
|
|
|
self._cond = Condition() # notify all tasks when state changes
|
|
|
|
|
|
|
|
self._parties = parties
|
|
|
|
self._state = _BarrierState.FILLING
|
|
|
|
self._count = 0 # count tasks in Barrier
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
res = super().__repr__()
|
|
|
|
extra = f'{self._state.value}'
|
|
|
|
if not self.broken:
|
|
|
|
extra += f', waiters:{self.n_waiting}/{self.parties}'
|
|
|
|
return f'<{res[1:-1]} [{extra}]>'
|
|
|
|
|
|
|
|
async def __aenter__(self):
|
|
|
|
# wait for the barrier reaches the parties number
|
|
|
|
# when start draining release and return index of waited task
|
|
|
|
return await self.wait()
|
|
|
|
|
|
|
|
async def __aexit__(self, *args):
|
|
|
|
pass
|
|
|
|
|
|
|
|
async def wait(self):
|
|
|
|
"""Wait for the barrier.
|
|
|
|
|
|
|
|
When the specified number of tasks have started waiting, they are all
|
|
|
|
simultaneously awoken.
|
|
|
|
Returns an unique and individual index number from 0 to 'parties-1'.
|
|
|
|
"""
|
|
|
|
async with self._cond:
|
|
|
|
await self._block() # Block while the barrier drains or resets.
|
|
|
|
try:
|
|
|
|
index = self._count
|
|
|
|
self._count += 1
|
|
|
|
if index + 1 == self._parties:
|
|
|
|
# We release the barrier
|
|
|
|
await self._release()
|
|
|
|
else:
|
|
|
|
await self._wait()
|
|
|
|
return index
|
|
|
|
finally:
|
|
|
|
self._count -= 1
|
|
|
|
# Wake up any tasks waiting for barrier to drain.
|
|
|
|
self._exit()
|
|
|
|
|
|
|
|
async def _block(self):
|
|
|
|
# Block until the barrier is ready for us,
|
|
|
|
# or raise an exception if it is broken.
|
|
|
|
#
|
|
|
|
# It is draining or resetting, wait until done
|
|
|
|
# unless a CancelledError occurs
|
|
|
|
await self._cond.wait_for(
|
|
|
|
lambda: self._state not in (
|
|
|
|
_BarrierState.DRAINING, _BarrierState.RESETTING
|
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
# see if the barrier is in a broken state
|
|
|
|
if self._state is _BarrierState.BROKEN:
|
|
|
|
raise exceptions.BrokenBarrierError("Barrier aborted")
|
|
|
|
|
|
|
|
async def _release(self):
|
|
|
|
# Release the tasks waiting in the barrier.
|
|
|
|
|
|
|
|
# Enter draining state.
|
|
|
|
# Next waiting tasks will be blocked until the end of draining.
|
|
|
|
self._state = _BarrierState.DRAINING
|
|
|
|
self._cond.notify_all()
|
|
|
|
|
|
|
|
async def _wait(self):
|
|
|
|
# Wait in the barrier until we are released. Raise an exception
|
|
|
|
# if the barrier is reset or broken.
|
|
|
|
|
|
|
|
# wait for end of filling
|
|
|
|
# unless a CancelledError occurs
|
|
|
|
await self._cond.wait_for(lambda: self._state is not _BarrierState.FILLING)
|
|
|
|
|
|
|
|
if self._state in (_BarrierState.BROKEN, _BarrierState.RESETTING):
|
|
|
|
raise exceptions.BrokenBarrierError("Abort or reset of barrier")
|
|
|
|
|
|
|
|
def _exit(self):
|
|
|
|
# If we are the last tasks to exit the barrier, signal any tasks
|
|
|
|
# waiting for the barrier to drain.
|
|
|
|
if self._count == 0:
|
|
|
|
if self._state in (_BarrierState.RESETTING, _BarrierState.DRAINING):
|
|
|
|
self._state = _BarrierState.FILLING
|
|
|
|
self._cond.notify_all()
|
|
|
|
|
|
|
|
async def reset(self):
|
|
|
|
"""Reset the barrier to the initial state.
|
|
|
|
|
|
|
|
Any tasks currently waiting will get the BrokenBarrier exception
|
|
|
|
raised.
|
|
|
|
"""
|
|
|
|
async with self._cond:
|
|
|
|
if self._count > 0:
|
|
|
|
if self._state is not _BarrierState.RESETTING:
|
|
|
|
#reset the barrier, waking up tasks
|
|
|
|
self._state = _BarrierState.RESETTING
|
|
|
|
else:
|
|
|
|
self._state = _BarrierState.FILLING
|
|
|
|
self._cond.notify_all()
|
|
|
|
|
|
|
|
async def abort(self):
|
|
|
|
"""Place the barrier into a 'broken' state.
|
|
|
|
|
|
|
|
Useful in case of error. Any currently waiting tasks and tasks
|
|
|
|
attempting to 'wait()' will have BrokenBarrierError raised.
|
|
|
|
"""
|
|
|
|
async with self._cond:
|
|
|
|
self._state = _BarrierState.BROKEN
|
|
|
|
self._cond.notify_all()
|
|
|
|
|
|
|
|
@property
|
|
|
|
def parties(self):
|
|
|
|
"""Return the number of tasks required to trip the barrier."""
|
|
|
|
return self._parties
|
|
|
|
|
|
|
|
@property
|
|
|
|
def n_waiting(self):
|
|
|
|
"""Return the number of tasks currently waiting at the barrier."""
|
|
|
|
if self._state is _BarrierState.FILLING:
|
|
|
|
return self._count
|
|
|
|
return 0
|
|
|
|
|
|
|
|
@property
|
|
|
|
def broken(self):
|
|
|
|
"""Return True if the barrier is in a broken state."""
|
|
|
|
return self._state is _BarrierState.BROKEN
|