@@ -336,22 +336,15 @@ class Semaphore:
336
336
337
337
Semaphores also support the context manager protocol.
338
338
339
- The first optional argument gives the initial value for the internal
339
+ The optional argument gives the initial value for the internal
340
340
counter; it defaults to 1. If the value given is less than 0,
341
341
ValueError is raised.
342
-
343
- The second optional argument determines if the semaphore can be released
344
- more than initial internal counter value; it defaults to False. If the
345
- value given is True and number of release() is more than number of
346
- successful acquire() calls ValueError is raised.
347
342
"""
348
343
349
- def __init__ (self , value = 1 , bound = False , * , loop = None ):
344
+ def __init__ (self , value = 1 , * , loop = None ):
350
345
if value < 0 :
351
346
raise ValueError ("Semaphore initial value must be >= 0" )
352
347
self ._value = value
353
- self ._bound = bound
354
- self ._bound_value = value
355
348
self ._waiters = collections .deque ()
356
349
self ._locked = (value == 0 )
357
350
if loop is not None :
@@ -402,17 +395,9 @@ def release(self):
402
395
"""Release a semaphore, incrementing the internal counter by one.
403
396
When it was zero on entry and another coroutine is waiting for it to
404
397
become larger than zero again, wake up that coroutine.
405
-
406
- If Semaphore is created with "bound" parameter equals true, then
407
- release() method checks to make sure its current value doesn't exceed
408
- its initial value. If it does, ValueError is raised.
409
398
"""
410
- if self ._bound and self ._value >= self ._bound_value :
411
- raise ValueError ('Semaphore released too many times' )
412
-
413
399
self ._value += 1
414
400
self ._locked = False
415
-
416
401
for waiter in self ._waiters :
417
402
if not waiter .done ():
418
403
waiter .set_result (True )
@@ -429,3 +414,20 @@ def __exit__(self, *args):
429
414
def __iter__ (self ):
430
415
yield from self .acquire ()
431
416
return self
417
+
418
+
419
+ class BoundedSemaphore (Semaphore ):
420
+ """A bounded semaphore implementation.
421
+
422
+ This raises ValueError in release() if it would increase the value
423
+ above the initial value.
424
+ """
425
+
426
+ def __init__ (self , value = 1 , * , loop = None ):
427
+ self ._bound_value = value
428
+ super ().__init__ (value , loop = loop )
429
+
430
+ def release (self ):
431
+ if self ._value >= self ._bound_value :
432
+ raise ValueError ('BoundedSemaphore released too many times' )
433
+ super ().release ()
0 commit comments