12

We're working in multithreaded python environment and need a mutual exclusion for a piece of code like:

lock = threading.Lock()
with lock:
    # get data from shared storage
    # process
    # put back to shared storage

Currently it seems to me that binary semaphore threading.Semaphore() and lock threading.Lock() will similarly serve for this. Are there some pitfalls or gainings if I switch from lock to binary semaphore or vice versa?

NOTE: code running inside greenthreads (if that changes situation)

Max Lobur
  • 5,662
  • 22
  • 35
  • I believe you can find a good explanation here https://stackoverflow.com/questions/62814/difference-between-binary-semaphore-and-mutex – Sanghyun Lee Apr 29 '22 at 21:06

2 Answers2

0

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.

-4

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.

GVH
  • 416
  • 3
  • 16