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