locks.py 19 KB

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