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