Class that implements a condition variable. A condition variable allows one or more threads to wait until they are notified by another thread. If the lock argument is given and not None, it must be a Lock or RLock object, and it is used as the underlying lock. Otherwise, a ne
| 229 | |
| 230 | |
| 231 | class Condition: |
| 232 | """Class that implements a condition variable. |
| 233 | |
| 234 | A condition variable allows one or more threads to wait until they are |
| 235 | notified by another thread. |
| 236 | |
| 237 | If the lock argument is given and not None, it must be a Lock or RLock |
| 238 | object, and it is used as the underlying lock. Otherwise, a new RLock object |
| 239 | is created and used as the underlying lock. |
| 240 | |
| 241 | """ |
| 242 | |
| 243 | def __init__(self, lock=None): |
| 244 | if lock is None: |
| 245 | lock = RLock() |
| 246 | self._lock = lock |
| 247 | # Export the lock's acquire() and release() methods |
| 248 | self.acquire = lock.acquire |
| 249 | self.release = lock.release |
| 250 | # If the lock defines _release_save() and/or _acquire_restore(), |
| 251 | # these override the default implementations (which just call |
| 252 | # release() and acquire() on the lock). Ditto for _is_owned(). |
| 253 | try: |
| 254 | self._release_save = lock._release_save |
| 255 | except AttributeError: |
| 256 | pass |
| 257 | try: |
| 258 | self._acquire_restore = lock._acquire_restore |
| 259 | except AttributeError: |
| 260 | pass |
| 261 | try: |
| 262 | self._is_owned = lock._is_owned |
| 263 | except AttributeError: |
| 264 | pass |
| 265 | self._waiters = _deque() |
| 266 | |
| 267 | def _at_fork_reinit(self): |
| 268 | self._lock._at_fork_reinit() |
| 269 | self._waiters.clear() |
| 270 | |
| 271 | def __enter__(self): |
| 272 | return self._lock.__enter__() |
| 273 | |
| 274 | def __exit__(self, *args): |
| 275 | return self._lock.__exit__(*args) |
| 276 | |
| 277 | def __repr__(self): |
| 278 | return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) |
| 279 | |
| 280 | def _release_save(self): |
| 281 | self._lock.release() # No state to save |
| 282 | |
| 283 | def _acquire_restore(self, x): |
| 284 | self._lock.acquire() # Ignore saved state |
| 285 | |
| 286 | def _is_owned(self): |
| 287 | # Return True if lock is owned by current_thread. |
| 288 | # This method is called only if _lock doesn't have _is_owned(). |