locks.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. """Synchronization primitives."""
  2. __all__ = ('Lock', 'Event', 'Condition', 'Semaphore',
  3. 'BoundedSemaphore', 'Barrier')
  4. import collections
  5. import enum
  6. from . import exceptions
  7. from . import mixins
  8. from . import tasks
  9. class _ContextManagerMixin:
  10. async def __aenter__(self):
  11. await self.acquire()
  12. # We have no use for the "as ..." clause in the with
  13. # statement for locks.
  14. return None
  15. async def __aexit__(self, exc_type, exc, tb):
  16. self.release()
  17. class Lock(_ContextManagerMixin, mixins._LoopBoundMixin):
  18. """Primitive lock objects.
  19. A primitive lock is a synchronization primitive that is not owned
  20. by a particular coroutine when locked. A primitive lock is in one
  21. of two states, 'locked' or 'unlocked'.
  22. It is created in the unlocked state. It has two basic methods,
  23. acquire() and release(). When the state is unlocked, acquire()
  24. changes the state to locked and returns immediately. When the
  25. state is locked, acquire() blocks until a call to release() in
  26. another coroutine changes it to unlocked, then the acquire() call
  27. resets it to locked and returns. The release() method should only
  28. be called in the locked state; it changes the state to unlocked
  29. and returns immediately. If an attempt is made to release an
  30. unlocked lock, a RuntimeError will be raised.
  31. When more than one coroutine is blocked in acquire() waiting for
  32. the state to turn to unlocked, only one coroutine proceeds when a
  33. release() call resets the state to unlocked; first coroutine which
  34. is blocked in acquire() is being processed.
  35. acquire() is a coroutine and should be called with 'await'.
  36. Locks also support the asynchronous context management protocol.
  37. 'async with lock' statement should be used.
  38. Usage:
  39. lock = Lock()
  40. ...
  41. await lock.acquire()
  42. try:
  43. ...
  44. finally:
  45. lock.release()
  46. Context manager usage:
  47. lock = Lock()
  48. ...
  49. async with lock:
  50. ...
  51. Lock objects can be tested for locking state:
  52. if not lock.locked():
  53. await lock.acquire()
  54. else:
  55. # lock is acquired
  56. ...
  57. """
  58. def __init__(self):
  59. self._waiters = None
  60. self._locked = False
  61. def __repr__(self):
  62. res = super().__repr__()
  63. extra = 'locked' if self._locked else 'unlocked'
  64. if self._waiters:
  65. extra = f'{extra}, waiters:{len(self._waiters)}'
  66. return f'<{res[1:-1]} [{extra}]>'
  67. def locked(self):
  68. """Return True if lock is acquired."""
  69. return self._locked
  70. async def acquire(self):
  71. """Acquire a lock.
  72. This method blocks until the lock is unlocked, then sets it to
  73. locked and returns True.
  74. """
  75. if (not self._locked and (self._waiters is None or
  76. all(w.cancelled() for w in self._waiters))):
  77. self._locked = True
  78. return True
  79. if self._waiters is None:
  80. self._waiters = collections.deque()
  81. fut = self._get_loop().create_future()
  82. self._waiters.append(fut)
  83. # Finally block should be called before the CancelledError
  84. # handling as we don't want CancelledError to call
  85. # _wake_up_first() and attempt to wake up itself.
  86. try:
  87. try:
  88. await fut
  89. finally:
  90. self._waiters.remove(fut)
  91. except exceptions.CancelledError:
  92. if not self._locked:
  93. self._wake_up_first()
  94. raise
  95. self._locked = True
  96. return True
  97. def release(self):
  98. """Release a lock.
  99. When the lock is locked, reset it to unlocked, and return.
  100. If any other coroutines are blocked waiting for the lock to become
  101. unlocked, allow exactly one of them to proceed.
  102. When invoked on an unlocked lock, a RuntimeError is raised.
  103. There is no return value.
  104. """
  105. if self._locked:
  106. self._locked = False
  107. self._wake_up_first()
  108. else:
  109. raise RuntimeError('Lock is not acquired.')
  110. def _wake_up_first(self):
  111. """Wake up the first waiter if it isn't done."""
  112. if not self._waiters:
  113. return
  114. try:
  115. fut = next(iter(self._waiters))
  116. except StopIteration:
  117. return
  118. # .done() necessarily means that a waiter will wake up later on and
  119. # either take the lock, or, if it was cancelled and lock wasn't
  120. # taken already, will hit this again and wake up a new waiter.
  121. if not fut.done():
  122. fut.set_result(True)
  123. class Event(mixins._LoopBoundMixin):
  124. """Asynchronous equivalent to threading.Event.
  125. Class implementing event objects. An event manages a flag that can be set
  126. to true with the set() method and reset to false with the clear() method.
  127. The wait() method blocks until the flag is true. The flag is initially
  128. false.
  129. """
  130. def __init__(self):
  131. self._waiters = collections.deque()
  132. self._value = False
  133. def __repr__(self):
  134. res = super().__repr__()
  135. extra = 'set' if self._value else 'unset'
  136. if self._waiters:
  137. extra = f'{extra}, waiters:{len(self._waiters)}'
  138. return f'<{res[1:-1]} [{extra}]>'
  139. def is_set(self):
  140. """Return True if and only if the internal flag is true."""
  141. return self._value
  142. def set(self):
  143. """Set the internal flag to true. All coroutines waiting for it to
  144. become true are awakened. Coroutine that call wait() once the flag is
  145. true will not block at all.
  146. """
  147. if not self._value:
  148. self._value = True
  149. for fut in self._waiters:
  150. if not fut.done():
  151. fut.set_result(True)
  152. def clear(self):
  153. """Reset the internal flag to false. Subsequently, coroutines calling
  154. wait() will block until set() is called to set the internal flag
  155. to true again."""
  156. self._value = False
  157. async def wait(self):
  158. """Block until the internal flag is true.
  159. If the internal flag is true on entry, return True
  160. immediately. Otherwise, block until another coroutine calls
  161. set() to set the flag to true, then return True.
  162. """
  163. if self._value:
  164. return True
  165. fut = self._get_loop().create_future()
  166. self._waiters.append(fut)
  167. try:
  168. await fut
  169. return True
  170. finally:
  171. self._waiters.remove(fut)
  172. class Condition(_ContextManagerMixin, mixins._LoopBoundMixin):
  173. """Asynchronous equivalent to threading.Condition.
  174. This class implements condition variable objects. A condition variable
  175. allows one or more coroutines to wait until they are notified by another
  176. coroutine.
  177. A new Lock object is created and used as the underlying lock.
  178. """
  179. def __init__(self, lock=None):
  180. if lock is None:
  181. lock = Lock()
  182. self._lock = lock
  183. # Export the lock's locked(), acquire() and release() methods.
  184. self.locked = lock.locked
  185. self.acquire = lock.acquire
  186. self.release = lock.release
  187. self._waiters = collections.deque()
  188. def __repr__(self):
  189. res = super().__repr__()
  190. extra = 'locked' if self.locked() else 'unlocked'
  191. if self._waiters:
  192. extra = f'{extra}, waiters:{len(self._waiters)}'
  193. return f'<{res[1:-1]} [{extra}]>'
  194. async def wait(self):
  195. """Wait until notified.
  196. If the calling coroutine has not acquired the lock when this
  197. method is called, a RuntimeError is raised.
  198. This method releases the underlying lock, and then blocks
  199. until it is awakened by a notify() or notify_all() call for
  200. the same condition variable in another coroutine. Once
  201. awakened, it re-acquires the lock and returns True.
  202. """
  203. if not self.locked():
  204. raise RuntimeError('cannot wait on un-acquired lock')
  205. self.release()
  206. try:
  207. fut = self._get_loop().create_future()
  208. self._waiters.append(fut)
  209. try:
  210. await fut
  211. return True
  212. finally:
  213. self._waiters.remove(fut)
  214. finally:
  215. # Must reacquire lock even if wait is cancelled
  216. cancelled = False
  217. while True:
  218. try:
  219. await self.acquire()
  220. break
  221. except exceptions.CancelledError:
  222. cancelled = True
  223. if cancelled:
  224. raise exceptions.CancelledError
  225. async def wait_for(self, predicate):
  226. """Wait until a predicate becomes true.
  227. The predicate should be a callable which result will be
  228. interpreted as a boolean value. The final predicate value is
  229. the return value.
  230. """
  231. result = predicate()
  232. while not result:
  233. await self.wait()
  234. result = predicate()
  235. return result
  236. def notify(self, n=1):
  237. """By default, wake up one coroutine waiting on this condition, if any.
  238. If the calling coroutine has not acquired the lock when this method
  239. is called, a RuntimeError is raised.
  240. This method wakes up at most n of the coroutines waiting for the
  241. condition variable; it is a no-op if no coroutines are waiting.
  242. Note: an awakened coroutine does not actually return from its
  243. wait() call until it can reacquire the lock. Since notify() does
  244. not release the lock, its caller should.
  245. """
  246. if not self.locked():
  247. raise RuntimeError('cannot notify on un-acquired lock')
  248. idx = 0
  249. for fut in self._waiters:
  250. if idx >= n:
  251. break
  252. if not fut.done():
  253. idx += 1
  254. fut.set_result(False)
  255. def notify_all(self):
  256. """Wake up all threads waiting on this condition. This method acts
  257. like notify(), but wakes up all waiting threads instead of one. If the
  258. calling thread has not acquired the lock when this method is called,
  259. a RuntimeError is raised.
  260. """
  261. self.notify(len(self._waiters))
  262. class Semaphore(_ContextManagerMixin, mixins._LoopBoundMixin):
  263. """A Semaphore implementation.
  264. A semaphore manages an internal counter which is decremented by each
  265. acquire() call and incremented by each release() call. The counter
  266. can never go below zero; when acquire() finds that it is zero, it blocks,
  267. waiting until some other thread calls release().
  268. Semaphores also support the context management protocol.
  269. The optional argument gives the initial value for the internal
  270. counter; it defaults to 1. If the value given is less than 0,
  271. ValueError is raised.
  272. """
  273. def __init__(self, value=1):
  274. if value < 0:
  275. raise ValueError("Semaphore initial value must be >= 0")
  276. self._waiters = None
  277. self._value = value
  278. def __repr__(self):
  279. res = super().__repr__()
  280. extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
  281. if self._waiters:
  282. extra = f'{extra}, waiters:{len(self._waiters)}'
  283. return f'<{res[1:-1]} [{extra}]>'
  284. def locked(self):
  285. """Returns True if semaphore cannot be acquired immediately."""
  286. return self._value == 0 or (
  287. any(not w.cancelled() for w in (self._waiters or ())))
  288. async def acquire(self):
  289. """Acquire a semaphore.
  290. If the internal counter is larger than zero on entry,
  291. decrement it by one and return True immediately. If it is
  292. zero on entry, block, waiting until some other coroutine has
  293. called release() to make it larger than 0, and then return
  294. True.
  295. """
  296. if not self.locked():
  297. self._value -= 1
  298. return True
  299. if self._waiters is None:
  300. self._waiters = collections.deque()
  301. fut = self._get_loop().create_future()
  302. self._waiters.append(fut)
  303. # Finally block should be called before the CancelledError
  304. # handling as we don't want CancelledError to call
  305. # _wake_up_first() and attempt to wake up itself.
  306. try:
  307. try:
  308. await fut
  309. finally:
  310. self._waiters.remove(fut)
  311. except exceptions.CancelledError:
  312. if not fut.cancelled():
  313. self._value += 1
  314. self._wake_up_next()
  315. raise
  316. if self._value > 0:
  317. self._wake_up_next()
  318. return True
  319. def release(self):
  320. """Release a semaphore, incrementing the internal counter by one.
  321. When it was zero on entry and another coroutine is waiting for it to
  322. become larger than zero again, wake up that coroutine.
  323. """
  324. self._value += 1
  325. self._wake_up_next()
  326. def _wake_up_next(self):
  327. """Wake up the first waiter that isn't done."""
  328. if not self._waiters:
  329. return
  330. for fut in self._waiters:
  331. if not fut.done():
  332. self._value -= 1
  333. fut.set_result(True)
  334. return
  335. class BoundedSemaphore(Semaphore):
  336. """A bounded semaphore implementation.
  337. This raises ValueError in release() if it would increase the value
  338. above the initial value.
  339. """
  340. def __init__(self, value=1):
  341. self._bound_value = value
  342. super().__init__(value)
  343. def release(self):
  344. if self._value >= self._bound_value:
  345. raise ValueError('BoundedSemaphore released too many times')
  346. super().release()
  347. class _BarrierState(enum.Enum):
  348. FILLING = 'filling'
  349. DRAINING = 'draining'
  350. RESETTING = 'resetting'
  351. BROKEN = 'broken'
  352. class Barrier(mixins._LoopBoundMixin):
  353. """Asyncio equivalent to threading.Barrier
  354. Implements a Barrier primitive.
  355. Useful for synchronizing a fixed number of tasks at known synchronization
  356. points. Tasks block on 'wait()' and are simultaneously awoken once they
  357. have all made their call.
  358. """
  359. def __init__(self, parties):
  360. """Create a barrier, initialised to 'parties' tasks."""
  361. if parties < 1:
  362. raise ValueError('parties must be > 0')
  363. self._cond = Condition() # notify all tasks when state changes
  364. self._parties = parties
  365. self._state = _BarrierState.FILLING
  366. self._count = 0 # count tasks in Barrier
  367. def __repr__(self):
  368. res = super().__repr__()
  369. extra = f'{self._state.value}'
  370. if not self.broken:
  371. extra += f', waiters:{self.n_waiting}/{self.parties}'
  372. return f'<{res[1:-1]} [{extra}]>'
  373. async def __aenter__(self):
  374. # wait for the barrier reaches the parties number
  375. # when start draining release and return index of waited task
  376. return await self.wait()
  377. async def __aexit__(self, *args):
  378. pass
  379. async def wait(self):
  380. """Wait for the barrier.
  381. When the specified number of tasks have started waiting, they are all
  382. simultaneously awoken.
  383. Returns an unique and individual index number from 0 to 'parties-1'.
  384. """
  385. async with self._cond:
  386. await self._block() # Block while the barrier drains or resets.
  387. try:
  388. index = self._count
  389. self._count += 1
  390. if index + 1 == self._parties:
  391. # We release the barrier
  392. await self._release()
  393. else:
  394. await self._wait()
  395. return index
  396. finally:
  397. self._count -= 1
  398. # Wake up any tasks waiting for barrier to drain.
  399. self._exit()
  400. async def _block(self):
  401. # Block until the barrier is ready for us,
  402. # or raise an exception if it is broken.
  403. #
  404. # It is draining or resetting, wait until done
  405. # unless a CancelledError occurs
  406. await self._cond.wait_for(
  407. lambda: self._state not in (
  408. _BarrierState.DRAINING, _BarrierState.RESETTING
  409. )
  410. )
  411. # see if the barrier is in a broken state
  412. if self._state is _BarrierState.BROKEN:
  413. raise exceptions.BrokenBarrierError("Barrier aborted")
  414. async def _release(self):
  415. # Release the tasks waiting in the barrier.
  416. # Enter draining state.
  417. # Next waiting tasks will be blocked until the end of draining.
  418. self._state = _BarrierState.DRAINING
  419. self._cond.notify_all()
  420. async def _wait(self):
  421. # Wait in the barrier until we are released. Raise an exception
  422. # if the barrier is reset or broken.
  423. # wait for end of filling
  424. # unless a CancelledError occurs
  425. await self._cond.wait_for(lambda: self._state is not _BarrierState.FILLING)
  426. if self._state in (_BarrierState.BROKEN, _BarrierState.RESETTING):
  427. raise exceptions.BrokenBarrierError("Abort or reset of barrier")
  428. def _exit(self):
  429. # If we are the last tasks to exit the barrier, signal any tasks
  430. # waiting for the barrier to drain.
  431. if self._count == 0:
  432. if self._state in (_BarrierState.RESETTING, _BarrierState.DRAINING):
  433. self._state = _BarrierState.FILLING
  434. self._cond.notify_all()
  435. async def reset(self):
  436. """Reset the barrier to the initial state.
  437. Any tasks currently waiting will get the BrokenBarrier exception
  438. raised.
  439. """
  440. async with self._cond:
  441. if self._count > 0:
  442. if self._state is not _BarrierState.RESETTING:
  443. #reset the barrier, waking up tasks
  444. self._state = _BarrierState.RESETTING
  445. else:
  446. self._state = _BarrierState.FILLING
  447. self._cond.notify_all()
  448. async def abort(self):
  449. """Place the barrier into a 'broken' state.
  450. Useful in case of error. Any currently waiting tasks and tasks
  451. attempting to 'wait()' will have BrokenBarrierError raised.
  452. """
  453. async with self._cond:
  454. self._state = _BarrierState.BROKEN
  455. self._cond.notify_all()
  456. @property
  457. def parties(self):
  458. """Return the number of tasks required to trip the barrier."""
  459. return self._parties
  460. @property
  461. def n_waiting(self):
  462. """Return the number of tasks currently waiting at the barrier."""
  463. if self._state is _BarrierState.FILLING:
  464. return self._count
  465. return 0
  466. @property
  467. def broken(self):
  468. """Return True if the barrier is in a broken state."""
  469. return self._state is _BarrierState.BROKEN