| 222 | # |
| 223 | |
| 224 | class Condition(object): |
| 225 | |
| 226 | def __init__(self, lock=None, *, ctx): |
| 227 | self._lock = lock or ctx.RLock() |
| 228 | self._sleeping_count = ctx.Semaphore(0) |
| 229 | self._woken_count = ctx.Semaphore(0) |
| 230 | self._wait_semaphore = ctx.Semaphore(0) |
| 231 | self._make_methods() |
| 232 | |
| 233 | def __getstate__(self): |
| 234 | context.assert_spawning(self) |
| 235 | return (self._lock, self._sleeping_count, |
| 236 | self._woken_count, self._wait_semaphore) |
| 237 | |
| 238 | def __setstate__(self, state): |
| 239 | (self._lock, self._sleeping_count, |
| 240 | self._woken_count, self._wait_semaphore) = state |
| 241 | self._make_methods() |
| 242 | |
| 243 | def __enter__(self): |
| 244 | return self._lock.__enter__() |
| 245 | |
| 246 | def __exit__(self, *args): |
| 247 | return self._lock.__exit__(*args) |
| 248 | |
| 249 | def _make_methods(self): |
| 250 | self.acquire = self._lock.acquire |
| 251 | self.release = self._lock.release |
| 252 | |
| 253 | def __repr__(self): |
| 254 | try: |
| 255 | num_waiters = (self._sleeping_count.get_value() - |
| 256 | self._woken_count.get_value()) |
| 257 | except Exception: |
| 258 | num_waiters = 'unknown' |
| 259 | return '<%s(%s, %s)>' % (self.__class__.__name__, self._lock, num_waiters) |
| 260 | |
| 261 | def wait(self, timeout=None): |
| 262 | assert self._lock._semlock._is_mine(), \ |
| 263 | 'must acquire() condition before using wait()' |
| 264 | |
| 265 | # indicate that this thread is going to sleep |
| 266 | self._sleeping_count.release() |
| 267 | |
| 268 | # release lock |
| 269 | count = self._lock._semlock._count() |
| 270 | for i in range(count): |
| 271 | self._lock.release() |
| 272 | |
| 273 | try: |
| 274 | # wait for notification or timeout |
| 275 | return self._wait_semaphore.acquire(True, timeout) |
| 276 | finally: |
| 277 | # indicate that this thread has woken |
| 278 | self._woken_count.release() |
| 279 | |
| 280 | # reacquire lock |
| 281 | for i in range(count): |
no outgoing calls
no test coverage detected
searching dependent graphs…