pyhton 信号量Semaphore和BoundedSemaphore


Semaphore和BoundedSemaphore两个,用起来好像没啥区别

都是定义信号量

sem=threading.BoundedSemaphore(5)
sem=threading.Semaphore(5)

sem.acquire()
#一系列操作

sem.release()

不过BoundedSemaphore相对Semaphore更工厂一些

BoundedSemaphore在调用release()的时候,会校验一下当前信号量的值,是否会大于初始值(只定义了5个信号量,释放了5次后,还要调用release)的场景,会抛出异常
Semaphore released too many times
    print(sem.release())
  File "D:\python\lib\threading.py", line 483, in release
    raise ValueError("Semaphore released too many times")
ValueError: Semaphore released too many times

而 Semaphore在这种场景下,release()的结果只是None,没有返回信号量对象,并不会抛出异常

import threading

#sem=threading.BoundedSemaphore(5)
sem=threading.Semaphore(5)
global num
num=0
def run():
    global num
    sem.acquire()
    num+=1
    if num>0:
        sem.release()
    print(sem.release())

for i in range(20):
    threading.Thread(target=run,args=()).start()
print(num)