diff options
author | Raymond Hettinger <rhettinger@users.noreply.github.com> | 2019-08-29 08:45:19 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-08-29 08:45:19 (GMT) |
commit | 35f6301d68bdb0517be284421782d64407dfe72c (patch) | |
tree | 2b25b22aa2800545bdcac6bbfe9ab36472e6542a /Lib/threading.py | |
parent | 0dac68f1e593c11612ed54af9edb865d398f3b05 (diff) | |
download | cpython-35f6301d68bdb0517be284421782d64407dfe72c.zip cpython-35f6301d68bdb0517be284421782d64407dfe72c.tar.gz cpython-35f6301d68bdb0517be284421782d64407dfe72c.tar.bz2 |
bpo-10978: Semaphores can release multiple threads at a time (GH-15588)
Diffstat (limited to 'Lib/threading.py')
-rw-r--r-- | Lib/threading.py | 24 |
1 files changed, 15 insertions, 9 deletions
diff --git a/Lib/threading.py b/Lib/threading.py index 32a3d7c..c3bbb19 100644 --- a/Lib/threading.py +++ b/Lib/threading.py @@ -439,16 +439,19 @@ class Semaphore: __enter__ = acquire - def release(self): - """Release a semaphore, incrementing the internal counter by one. + def release(self, n=1): + """Release a semaphore, incrementing the internal counter by one or more. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. """ + if n < 1: + raise ValueError('n must be one or more') with self._cond: - self._value += 1 - self._cond.notify() + self._value += n + for i in range(n): + self._cond.notify() def __exit__(self, t, v, tb): self.release() @@ -475,8 +478,8 @@ class BoundedSemaphore(Semaphore): Semaphore.__init__(self, value) self._initial_value = value - def release(self): - """Release a semaphore, incrementing the internal counter by one. + def release(self, n=1): + """Release a semaphore, incrementing the internal counter by one or more. When the counter is zero on entry and another thread is waiting for it to become larger than zero again, wake up that thread. @@ -485,11 +488,14 @@ class BoundedSemaphore(Semaphore): raise a ValueError. """ + if n < 1: + raise ValueError('n must be one or more') with self._cond: - if self._value >= self._initial_value: + if self._value + n > self._initial_value: raise ValueError("Semaphore released too many times") - self._value += 1 - self._cond.notify() + self._value += n + for i in range(n): + self._cond.notify() class Event: |