PageRenderTime 25ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/Windows/Python3.8/WPy64-3830/WPy64-3830/python-3.8.3.amd64/Lib/asyncio/locks.py

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