locks.py 14 KB

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