[Python-Dev] threading.Semaphore()'s counter can become negative for non-ints

T.B. bauertomer at gmail.com
Sat Jan 28 20:59:10 CET 2012

Hello python-dev,

This is probably worth of a bug report: While looking at threading.py I 
noticed that Semaphore's counter can go below zero. This is opposed to 
the docs: "The counter can never go below zero; ...". Just try:

import threading
s = threading.Semaphore(0.5)
# You can now acquire s as many times as you want!
# even when s._value < 0.

The fix is tiny:
diff -r 265d35e8fe82 Lib/threading.py
--- a/Lib/threading.py  Fri Jan 27 21:17:04 2012 +0000
+++ b/Lib/threading.py  Sat Jan 28 21:22:04 2012 +0200
@@ -322,7 +321,7 @@
          rc = False
          endtime = None
-        while self._value == 0:
+        while self._value <= 0:
              if not blocking:
              if __debug__:

Which is better than forcing s._value to be an int.
I also think that the docs should be updated to reflect that the counter 
is not compared to be equal to zero, but non-positive. e.g. "when 
acquire() finds that it is zero...", "If it is zero on entry, block...".

On another commit: Regarding http://bugs.python.org/issue9346, an unused 
import was left:
-from collections import deque


More information about the Python-Dev mailing list