locks.py 15 KB

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