0

if binary semaphore can protect a resource atomically, then what is the benefit of mutex.

For example,

sem_init(&sem, 0, 1);
sem_wait(&sem);
critical session;
sem_post(&sem);

Please clarify any benefits of mutex over semaphore.

2 Answers 2

2

According to "Linux Kernel Development" by Robert Love (3rd edition) a mutex is a more recent invention than the semaphore "but has a simpler interface, more efficient performance, and additional constraints on its use" (p.195). While similar to a semaphore with a count of one, there is no possibility for higher counts as is possible with a semaphore. Also, only one task can hold the mutex, the locker must only unlock the mutex (i.e. no unlocking from some other context), recursive locks and unlocks are forbidden, a process cannot exit while holding a mutex, a mutex cannot be acquired by an interrupt handler or "bottom half", and can only be managed via the official API. Also there is a debugging mode to help look for violations of these above constraints.

The text recommends the use of a mutex by default unless one of the above constraints is problematical. In particular, a mutex is preferred for long lock times, and require for things that must sleep while holding a lock. (There is also related discussion about mutex vs. spin locks that might be worth reading about.)

0

With a mutex, only the thread that locked the mutex can unlock that mutex. However, any thread can increment or decrement a semaphore.

Not the answer you're looking for? Browse other questions tagged .