Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to use binary semaphore when mutex are available?

While reading about binary semaphore and mutex I found the following difference:

Both can have value 0 and 1, but mutex can be unlocked by the same thread which has acquired the mutex lock. A thread which acquires mutex lock can have priority inversion in case a higher priority process wants to acquire the same mutex whereas this is not the case with binary semaphore.

So where should I use binary semaphores? Can anyone cite an example?

EDIT: I think I have figured out the working of both. Basically binary semaphore offer synchronization whereas mutex offer locking mechanism. I read some examples from Galvin OS book to make it more clear.

like image 406
dejavu Avatar asked Jul 17 '12 17:07

dejavu


People also ask

Can you use binary semaphores to serve as a mutex?

A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.

Where are binary semaphores used?

A binary semaphore can be used to control access to a single resource. In particular, it can be used to enforce mutual exclusion for a critical section in user code. In this instance, the semaphore would be created with an initial count of one to indicate that no task is executing the critical section of code.

When should we use mutex and when should we use semaphore?

The correct use of a semaphore is for signaling from one task to another. A mutex is meant to be taken and released, always in that order, by each task that uses the shared resource it protects. By contrast, tasks that use semaphores either signal or wait—not both.

In which conditions a mutex is especially useful as compared to binary or counting semaphores?

Main difference between Mutex and Binary semaphore is in Mutext if thread lock the critical section then it has to unlock critical section no other thread can unlock it, but in case of Binary semaphore if one thread locks critical section using wait(s) function then value of s become "0" and no one can access it until ...


1 Answers

One typical situation where I find binary semaphores very useful is for thread initialization where the thread will read from a structure owned by the parent thread. The parent thread needs to wait for the new thread to read the shared data from the structure before it can let the structure's lifetime end (by leaving its scope, for instance). With a binary semaphore, all you have to do is initialize the semaphore value to zero and have the child post it while the parent waits on it. Without semaphores, you'd need a mutex and condition variable and much uglier program logic for using them.

like image 96
R.. GitHub STOP HELPING ICE Avatar answered Oct 11 '22 10:10

R.. GitHub STOP HELPING ICE