Home > Blockchain >  Usage of mutex and binary semaphore
Usage of mutex and binary semaphore

Time:11-02

So from my understanding, mutex and binary semaphore are very similar but I just want to know what are some specific application or circumstances that using mutex is better than binary semaphore or viceversa

CodePudding user response:

One big difference between a mutex and a binary semaphore is that a thread must not unlock a mutex locked by another thread (the thread locking the mutex is the unique ownership): a mutex is only meant to be used for critical sections. Wait conditions should be used in this case. A semaphore could be used to do that though it is a bit unusual. There are some other points about priority inversion and safety you can find here.

CodePudding user response:

Generally speaking—since you did not mention any particular library or programming language—mutex and binary semaphore are very close to the same thing.

Binary semaphore is a specialization of the more general counting semaphore, which was invented way back in the early 1960s. It is a surprisingly versatile thing (see The Little Book of Semaphores, and back in the day, it was imagined that semaphore would be the lowest-level API, that would be built-in to many different operating systems to provide the bedrock upon which other, portable synchronization methods and algorithms could be built.

In my personal opinion, if you use something called "mutex" or "lock," then you should use it for one thing only: Use it to prevent threads from interfering with each other when they access shared variables. Whenever you think you want to use a mutex to let one thread send some kind of a signal to some other thread, then that's when you should reach for "semaphore." Even though they both do practically the same thing, using the one with the right name will help other people who read your code to understand what you are doing.

  • Related