logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

locks.py (13703B)


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