locks.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. """Synchronization primitives."""
  2. __all__ = ('Lock', 'Event', 'Condition', 'Semaphore', 'BoundedSemaphore')
  3. import collections
  4. import warnings
  5. from . import events
  6. from . import futures
  7. from .coroutines import coroutine
  8. class _ContextManager:
  9. """Context manager.
  10. This enables the following idiom for acquiring and releasing a
  11. lock around a block:
  12. with (yield from lock):
  13. <block>
  14. while failing loudly when accidentally using:
  15. with lock:
  16. <block>
  17. Deprecated, use 'async with' statement:
  18. async with lock:
  19. <block>
  20. """
  21. def __init__(self, lock):
  22. self._lock = lock
  23. def __enter__(self):
  24. # We have no use for the "as ..." clause in the with
  25. # statement for locks.
  26. return None
  27. def __exit__(self, *args):
  28. try:
  29. self._lock.release()
  30. finally:
  31. self._lock = None # Crudely prevent reuse.
  32. class _ContextManagerMixin:
  33. def __enter__(self):
  34. raise RuntimeError(
  35. '"yield from" should be used as context manager expression')
  36. def __exit__(self, *args):
  37. # This must exist because __enter__ exists, even though that
  38. # always raises; that's how the with-statement works.
  39. pass
  40. @coroutine
  41. def __iter__(self):
  42. # This is not a coroutine. It is meant to enable the idiom:
  43. #
  44. # with (yield from lock):
  45. # <block>
  46. #
  47. # as an alternative to:
  48. #
  49. # yield from lock.acquire()
  50. # try:
  51. # <block>
  52. # finally:
  53. # lock.release()
  54. # Deprecated, use 'async with' statement:
  55. # async with lock:
  56. # <block>
  57. warnings.warn("'with (yield from lock)' is deprecated "
  58. "use 'async with lock' instead",
  59. DeprecationWarning, stacklevel=2)
  60. yield from self.acquire()
  61. return _ContextManager(self)
  62. async def __acquire_ctx(self):
  63. await self.acquire()
  64. return _ContextManager(self)
  65. def __await__(self):
  66. warnings.warn("'with await lock' is deprecated "
  67. "use 'async with lock' instead",
  68. DeprecationWarning, stacklevel=2)
  69. # To make "with await lock" work.
  70. return self.__acquire_ctx().__await__()
  71. async def __aenter__(self):
  72. await self.acquire()
  73. # We have no use for the "as ..." clause in the with
  74. # statement for locks.
  75. return None
  76. async def __aexit__(self, exc_type, exc, tb):
  77. self.release()
  78. class Lock(_ContextManagerMixin):
  79. """Primitive lock objects.
  80. A primitive lock is a synchronization primitive that is not owned
  81. by a particular coroutine when locked. A primitive lock is in one
  82. of two states, 'locked' or 'unlocked'.
  83. It is created in the unlocked state. It has two basic methods,
  84. acquire() and release(). When the state is unlocked, acquire()
  85. changes the state to locked and returns immediately. When the
  86. state is locked, acquire() blocks until a call to release() in
  87. another coroutine changes it to unlocked, then the acquire() call
  88. resets it to locked and returns. The release() method should only
  89. be called in the locked state; it changes the state to unlocked
  90. and returns immediately. If an attempt is made to release an
  91. unlocked lock, a RuntimeError will be raised.
  92. When more than one coroutine is blocked in acquire() waiting for
  93. the state to turn to unlocked, only one coroutine proceeds when a
  94. release() call resets the state to unlocked; first coroutine which
  95. is blocked in acquire() is being processed.
  96. acquire() is a coroutine and should be called with 'await'.
  97. Locks also support the asynchronous context management protocol.
  98. 'async with lock' statement should be used.
  99. Usage:
  100. lock = Lock()
  101. ...
  102. await lock.acquire()
  103. try:
  104. ...
  105. finally:
  106. lock.release()
  107. Context manager usage:
  108. lock = Lock()
  109. ...
  110. async with lock:
  111. ...
  112. Lock objects can be tested for locking state:
  113. if not lock.locked():
  114. await lock.acquire()
  115. else:
  116. # lock is acquired
  117. ...
  118. """
  119. def __init__(self, *, loop=None):
  120. self._waiters = collections.deque()
  121. self._locked = False
  122. if loop is not None:
  123. self._loop = loop
  124. else:
  125. self._loop = events.get_event_loop()
  126. def __repr__(self):
  127. res = super().__repr__()
  128. extra = 'locked' if self._locked else 'unlocked'
  129. if self._waiters:
  130. extra = f'{extra}, waiters:{len(self._waiters)}'
  131. return f'<{res[1:-1]} [{extra}]>'
  132. def locked(self):
  133. """Return True if lock is acquired."""
  134. return self._locked
  135. async def acquire(self):
  136. """Acquire a lock.
  137. This method blocks until the lock is unlocked, then sets it to
  138. locked and returns True.
  139. """
  140. if not self._locked and all(w.cancelled() for w in self._waiters):
  141. self._locked = True
  142. return True
  143. fut = self._loop.create_future()
  144. self._waiters.append(fut)
  145. # Finally block should be called before the CancelledError
  146. # handling as we don't want CancelledError to call
  147. # _wake_up_first() and attempt to wake up itself.
  148. try:
  149. try:
  150. await fut
  151. finally:
  152. self._waiters.remove(fut)
  153. except futures.CancelledError:
  154. if not self._locked:
  155. self._wake_up_first()
  156. raise
  157. self._locked = True
  158. return True
  159. def release(self):
  160. """Release a lock.
  161. When the lock is locked, reset it to unlocked, and return.
  162. If any other coroutines are blocked waiting for the lock to become
  163. unlocked, allow exactly one of them to proceed.
  164. When invoked on an unlocked lock, a RuntimeError is raised.
  165. There is no return value.
  166. """
  167. if self._locked:
  168. self._locked = False
  169. self._wake_up_first()
  170. else:
  171. raise RuntimeError('Lock is not acquired.')
  172. def _wake_up_first(self):
  173. """Wake up the first waiter if it isn't done."""
  174. try:
  175. fut = next(iter(self._waiters))
  176. except StopIteration:
  177. return
  178. # .done() necessarily means that a waiter will wake up later on and
  179. # either take the lock, or, if it was cancelled and lock wasn't
  180. # taken already, will hit this again and wake up a new waiter.
  181. if not fut.done():
  182. fut.set_result(True)
  183. class Event:
  184. """Asynchronous equivalent to threading.Event.
  185. Class implementing event objects. An event manages a flag that can be set
  186. to true with the set() method and reset to false with the clear() method.
  187. The wait() method blocks until the flag is true. The flag is initially
  188. false.
  189. """
  190. def __init__(self, *, loop=None):
  191. self._waiters = collections.deque()
  192. self._value = False
  193. if loop is not None:
  194. self._loop = loop
  195. else:
  196. self._loop = events.get_event_loop()
  197. def __repr__(self):
  198. res = super().__repr__()
  199. extra = 'set' if self._value else 'unset'
  200. if self._waiters:
  201. extra = f'{extra}, waiters:{len(self._waiters)}'
  202. return f'<{res[1:-1]} [{extra}]>'
  203. def is_set(self):
  204. """Return True if and only if the internal flag is true."""
  205. return self._value
  206. def set(self):
  207. """Set the internal flag to true. All coroutines waiting for it to
  208. become true are awakened. Coroutine that call wait() once the flag is
  209. true will not block at all.
  210. """
  211. if not self._value:
  212. self._value = True
  213. for fut in self._waiters:
  214. if not fut.done():
  215. fut.set_result(True)
  216. def clear(self):
  217. """Reset the internal flag to false. Subsequently, coroutines calling
  218. wait() will block until set() is called to set the internal flag
  219. to true again."""
  220. self._value = False
  221. async def wait(self):
  222. """Block until the internal flag is true.
  223. If the internal flag is true on entry, return True
  224. immediately. Otherwise, block until another coroutine calls
  225. set() to set the flag to true, then return True.
  226. """
  227. if self._value:
  228. return True
  229. fut = self._loop.create_future()
  230. self._waiters.append(fut)
  231. try:
  232. await fut
  233. return True
  234. finally:
  235. self._waiters.remove(fut)
  236. class Condition(_ContextManagerMixin):
  237. """Asynchronous equivalent to threading.Condition.
  238. This class implements condition variable objects. A condition variable
  239. allows one or more coroutines to wait until they are notified by another
  240. coroutine.
  241. A new Lock object is created and used as the underlying lock.
  242. """
  243. def __init__(self, lock=None, *, loop=None):
  244. if loop is not None:
  245. self._loop = loop
  246. else:
  247. self._loop = events.get_event_loop()
  248. if lock is None:
  249. lock = Lock(loop=self._loop)
  250. elif lock._loop is not self._loop:
  251. raise ValueError("loop argument must agree with lock")
  252. self._lock = lock
  253. # Export the lock's locked(), acquire() and release() methods.
  254. self.locked = lock.locked
  255. self.acquire = lock.acquire
  256. self.release = lock.release
  257. self._waiters = collections.deque()
  258. def __repr__(self):
  259. res = super().__repr__()
  260. extra = 'locked' if self.locked() else 'unlocked'
  261. if self._waiters:
  262. extra = f'{extra}, waiters:{len(self._waiters)}'
  263. return f'<{res[1:-1]} [{extra}]>'
  264. async def wait(self):
  265. """Wait until notified.
  266. If the calling coroutine has not acquired the lock when this
  267. method is called, a RuntimeError is raised.
  268. This method releases the underlying lock, and then blocks
  269. until it is awakened by a notify() or notify_all() call for
  270. the same condition variable in another coroutine. Once
  271. awakened, it re-acquires the lock and returns True.
  272. """
  273. if not self.locked():
  274. raise RuntimeError('cannot wait on un-acquired lock')
  275. self.release()
  276. try:
  277. fut = self._loop.create_future()
  278. self._waiters.append(fut)
  279. try:
  280. await fut
  281. return True
  282. finally:
  283. self._waiters.remove(fut)
  284. finally:
  285. # Must reacquire lock even if wait is cancelled
  286. cancelled = False
  287. while True:
  288. try:
  289. await self.acquire()
  290. break
  291. except futures.CancelledError:
  292. cancelled = True
  293. if cancelled:
  294. raise futures.CancelledError
  295. async def wait_for(self, predicate):
  296. """Wait until a predicate becomes true.
  297. The predicate should be a callable which result will be
  298. interpreted as a boolean value. The final predicate value is
  299. the return value.
  300. """
  301. result = predicate()
  302. while not result:
  303. await self.wait()
  304. result = predicate()
  305. return result
  306. def notify(self, n=1):
  307. """By default, wake up one coroutine waiting on this condition, if any.
  308. If the calling coroutine has not acquired the lock when this method
  309. is called, a RuntimeError is raised.
  310. This method wakes up at most n of the coroutines waiting for the
  311. condition variable; it is a no-op if no coroutines are waiting.
  312. Note: an awakened coroutine does not actually return from its
  313. wait() call until it can reacquire the lock. Since notify() does
  314. not release the lock, its caller should.
  315. """
  316. if not self.locked():
  317. raise RuntimeError('cannot notify on un-acquired lock')
  318. idx = 0
  319. for fut in self._waiters:
  320. if idx >= n:
  321. break
  322. if not fut.done():
  323. idx += 1
  324. fut.set_result(False)
  325. def notify_all(self):
  326. """Wake up all threads waiting on this condition. This method acts
  327. like notify(), but wakes up all waiting threads instead of one. If the
  328. calling thread has not acquired the lock when this method is called,
  329. a RuntimeError is raised.
  330. """
  331. self.notify(len(self._waiters))
  332. class Semaphore(_ContextManagerMixin):
  333. """A Semaphore implementation.
  334. A semaphore manages an internal counter which is decremented by each
  335. acquire() call and incremented by each release() call. The counter
  336. can never go below zero; when acquire() finds that it is zero, it blocks,
  337. waiting until some other thread calls release().
  338. Semaphores also support the context management protocol.
  339. The optional argument gives the initial value for the internal
  340. counter; it defaults to 1. If the value given is less than 0,
  341. ValueError is raised.
  342. """
  343. def __init__(self, value=1, *, loop=None):
  344. if value < 0:
  345. raise ValueError("Semaphore initial value must be >= 0")
  346. self._value = value
  347. self._waiters = collections.deque()
  348. if loop is not None:
  349. self._loop = loop
  350. else:
  351. self._loop = events.get_event_loop()
  352. def __repr__(self):
  353. res = super().__repr__()
  354. extra = 'locked' if self.locked() else f'unlocked, value:{self._value}'
  355. if self._waiters:
  356. extra = f'{extra}, waiters:{len(self._waiters)}'
  357. return f'<{res[1:-1]} [{extra}]>'
  358. def _wake_up_next(self):
  359. while self._waiters:
  360. waiter = self._waiters.popleft()
  361. if not waiter.done():
  362. waiter.set_result(None)
  363. return
  364. def locked(self):
  365. """Returns True if semaphore can not be acquired immediately."""
  366. return self._value == 0
  367. async def acquire(self):
  368. """Acquire a semaphore.
  369. If the internal counter is larger than zero on entry,
  370. decrement it by one and return True immediately. If it is
  371. zero on entry, block, waiting until some other coroutine has
  372. called release() to make it larger than 0, and then return
  373. True.
  374. """
  375. while self._value <= 0:
  376. fut = self._loop.create_future()
  377. self._waiters.append(fut)
  378. try:
  379. await fut
  380. except:
  381. # See the similar code in Queue.get.
  382. fut.cancel()
  383. if self._value > 0 and not fut.cancelled():
  384. self._wake_up_next()
  385. raise
  386. self._value -= 1
  387. return True
  388. def release(self):
  389. """Release a semaphore, incrementing the internal counter by one.
  390. When it was zero on entry and another coroutine is waiting for it to
  391. become larger than zero again, wake up that coroutine.
  392. """
  393. self._value += 1
  394. self._wake_up_next()
  395. class BoundedSemaphore(Semaphore):
  396. """A bounded semaphore implementation.
  397. This raises ValueError in release() if it would increase the value
  398. above the initial value.
  399. """
  400. def __init__(self, value=1, *, loop=None):
  401. self._bound_value = value
  402. super().__init__(value, loop=loop)
  403. def release(self):
  404. if self._value >= self._bound_value:
  405. raise ValueError('BoundedSemaphore released too many times')
  406. super().release()