Acquire a semaphore, decrementing the internal counter by one. When invoked without arguments: if the internal counter is larger than zero on entry, decrement it by one and return immediately. If it is zero on entry, block, waiting until some other thread has called release(
(self, blocking=True, timeout=None)
| 473 | f" value={self._value}>") |
| 474 | |
| 475 | def acquire(self, blocking=True, timeout=None): |
| 476 | """Acquire a semaphore, decrementing the internal counter by one. |
| 477 | |
| 478 | When invoked without arguments: if the internal counter is larger than |
| 479 | zero on entry, decrement it by one and return immediately. If it is zero |
| 480 | on entry, block, waiting until some other thread has called release() to |
| 481 | make it larger than zero. This is done with proper interlocking so that |
| 482 | if multiple acquire() calls are blocked, release() will wake exactly one |
| 483 | of them up. The implementation may pick one at random, so the order in |
| 484 | which blocked threads are awakened should not be relied on. There is no |
| 485 | return value in this case. |
| 486 | |
| 487 | When invoked with blocking set to true, do the same thing as when called |
| 488 | without arguments, and return true. |
| 489 | |
| 490 | When invoked with blocking set to false, do not block. If a call without |
| 491 | an argument would block, return false immediately; otherwise, do the |
| 492 | same thing as when called without arguments, and return true. |
| 493 | |
| 494 | When invoked with a timeout other than None, it will block for at |
| 495 | most timeout seconds. If acquire does not complete successfully in |
| 496 | that interval, return false. Return true otherwise. |
| 497 | |
| 498 | """ |
| 499 | if not blocking and timeout is not None: |
| 500 | raise ValueError("can't specify timeout for non-blocking acquire") |
| 501 | rc = False |
| 502 | endtime = None |
| 503 | with self._cond: |
| 504 | while self._value == 0: |
| 505 | if not blocking: |
| 506 | break |
| 507 | if timeout is not None: |
| 508 | if endtime is None: |
| 509 | endtime = _time() + timeout |
| 510 | else: |
| 511 | timeout = endtime - _time() |
| 512 | if timeout <= 0: |
| 513 | break |
| 514 | self._cond.wait(timeout) |
| 515 | else: |
| 516 | self._value -= 1 |
| 517 | rc = True |
| 518 | return rc |
| 519 | |
| 520 | __enter__ = acquire |
| 521 |