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

T.B. bauertomer at gmail.com
Mon Jan 30 23:11:04 CET 2012

On 2012-01-30 20:52, Guido van Rossum wrote:
> TB, what's your use case for passing a float to a semaphore?
> Semaphores are conceptually tied to integers. You've kept arguing a
> few times now that the workaround you need are clumsy, but you've not
> explained why you're passing floats in the first place. A "fractional
> resource" just doesn't sound like a real use case to me.

Not an example from real life and certainly not one that can't be worked 
around; rather a thing that caught my eyes while looking at 
Lib/threading.py: Say you have a "known" constant guaranteed bandwidth 
and you need to split it among several connections which each of them 
take a known fixed amount of bandwidth (no more, no less).
How many connections can I reliably serve? 

Side note: If someone really want a discrete math implementation of a 
semaphore, you can replace _value with a list of resources. Then you 
check in acquire() "while not self._resources:" and pop a resource. In 
that case when a semaphore is used as a context manager it can have a 
useful 'as' clause. To me it seems too complicated for something that 
should be simple like a semaphore.


More information about the Python-Dev mailing list