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 new RLoc
| 269 | |
| 270 | |
| 271 | class Condition: |
| 272 | """Class that implements a condition variable. |
| 273 | |
| 274 | A condition variable allows one or more threads to wait until they are |
| 275 | notified by another thread. |
| 276 | |
| 277 | If the lock argument is given and not None, it must be a Lock or RLock |
| 278 | object, and it is used as the underlying lock. Otherwise, a new RLock object |
| 279 | is created and used as the underlying lock. |
| 280 | |
| 281 | """ |
| 282 | |
| 283 | def __init__(self, lock=None): |
| 284 | if lock is None: |
| 285 | lock = RLock() |
| 286 | self._lock = lock |
| 287 | # Export the lock's acquire(), release(), and locked() methods |
| 288 | self.acquire = lock.acquire |
| 289 | self.release = lock.release |
| 290 | self.locked = lock.locked |
| 291 | # If the lock defines _release_save() and/or _acquire_restore(), |
| 292 | # these override the default implementations (which just call |
| 293 | # release() and acquire() on the lock). Ditto for _is_owned(). |
| 294 | if hasattr(lock, '_release_save'): |
| 295 | self._release_save = lock._release_save |
| 296 | if hasattr(lock, '_acquire_restore'): |
| 297 | self._acquire_restore = lock._acquire_restore |
| 298 | if hasattr(lock, '_is_owned'): |
| 299 | self._is_owned = lock._is_owned |
| 300 | self._waiters = _deque() |
| 301 | |
| 302 | def _at_fork_reinit(self): |
| 303 | self._lock._at_fork_reinit() |
| 304 | self._waiters.clear() |
| 305 | |
| 306 | def __enter__(self): |
| 307 | return self._lock.__enter__() |
| 308 | |
| 309 | def __exit__(self, *args): |
| 310 | return self._lock.__exit__(*args) |
| 311 | |
| 312 | def __repr__(self): |
| 313 | return "<Condition(%s, %d)>" % (self._lock, len(self._waiters)) |
| 314 | |
| 315 | def _release_save(self): |
| 316 | self._lock.release() # No state to save |
| 317 | |
| 318 | def _acquire_restore(self, x): |
| 319 | self._lock.acquire() # Ignore saved state |
| 320 | |
| 321 | def _is_owned(self): |
| 322 | # Return True if lock is owned by current_thread. |
| 323 | # This method is called only if _lock doesn't have _is_owned(). |
| 324 | if self._lock.acquire(False): |
| 325 | self._lock.release() |
| 326 | return False |
| 327 | else: |
| 328 | return True |