Python binary semaphore VS lock Python binary semaphore VS lock multithreading multithreading

Python binary semaphore VS lock


It can be said that Semaphore is an advanced version of Lock. Semaphore has a custom number to control multiple threads to access resources. But there is only one with Lock.


threading.Semaphore() uses a threading.Lock() object internally as a monitor. When Semaphore.acquire() is called, the semaphore object calls acquire on its Lock object, decrements its value, and releases the lock.

From this it follows that a binary Semaphore is really just a wrapper around a Lock. I cannot think of any functional difference between the two, except that with Semaphore you can pass the optional verbose = True parameter for debugging purposes, and have the option to call acquire with blocking = False.