python threading模块还提供古老的信号量(semaphore)功能。
This is one of the oldest synchronization primitives in the history of computer science, invented by the early Dutch computer scientist Edsger W. Dijkstra (he used the names P() and V() instead of acquire() and release()). A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release().
信号量通过其内部的一个int变量来控制行为,P和V操作时原子的。默认情况下,threading.Semaphore创建的信号量,内部int的初始值为1,此时行为模式与一个lock互斥量没啥区别。不过,有一个细节,信号量的release(即V操作)会增加其内部的int值,而且可以多次release。
>>> import threading
>>> sp = threading.Semaphore()
>>> sp.acquire()
True
>>> sp.release()
>>> sp.release()
信号量多