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