The difference between semaphore and mutex is the difference between a mechanism and a template . The difference in their purpose ( intention ) and how they work ( behavioral ).
mutex , barrier , pipeline are parallel programming patterns . mutex used ( intended ) to protect the critical section and ensure mutual exclusion . barrier forces agents (thread / process) to continue to wait for each other.
One of the characteristics ( behavior ) of the mutex template is that only an authorized agent (processes or thread) can enter the critical section and only that agent can voluntarily get from this.
There are times when mutex allows a one-time agent. There are times when it allows several agents (multiple readers) and prohibit some other agents (writers).
semaphore is a mechanism that you can use ( intended ) to implement various patterns. This ( behavior ) is usually a flag (possibly protected by mutual exclusion). (One interesting fact - even the mutex template can be used to implement the semaphore).
In a popular culture, semaphores are mechanisms provided by the kernels, and mutexes provided by the user space library.
Note that there are misconceptions about semaphores and mutexes . It says that semaphores are used for synchronization . And mutexes has ownership . This is due to popular OS books. But truth is all mutexes, semaphores, and barriers used for synchronization . The purpose of the mutex is not ownership , but mutual exclusion . This fallacy led to a popular interview asking about the difference mutexes and binary-semaphores .
Summary
intention
- mutex, mutual exclusion
- semaphore, implement parallel design patterns
behavior
- mutex, only the authorized agent enters the critical section and only he (they) can exit
- semaphore, enter if the flag says "go", otherwise wait until someone changes the flag
In a project perspective, mutex more like a state-pattern , where an algorithm selected by the state can change state. binary-semaphore more like a strategy-pattern , where an external algorithm can change state and, ultimately, the algorithm / strategy chosen to run.
shuva May 17 '16 at 17:30 2016-05-17 17:30
source share