What is the difference between semaphores and mutex provided by pthread library ?
semaphores have a synchronized counter and mutex's are just binary (true / false).
A semaphore is often used as a definitive mechanism for answering how many elements of a resource are in use -- e.g., an object that represents n worker threads might use a semaphore to count how many worker threads are available.
Truth is you can represent a semaphore by an INT that is synchronized by a mutex.
The difference between the semaphore
and mutex
is the difference between mechanism and pattern. The difference is in their purpose (intent)and how they work(behavioral).
The mutex
, barrier
, pipeline
are parallel programming patterns. Mutex
is used(intended) to protect a critical section
and ensure mutual exclusion
. Barrier
makes the agents(thread/process) keep waiting for each other.
One of the feature(behavior) of mutex
pattern is that only allowed agent(s)(process or thread) can enter a critical section and only that agent(s) can voluntarily get out of that.
There are cases when mutex
allows single agent at a time. There are cases where it allows multiple agents(multiple readers) and disallow some other agents(writers).
The semaphore
is a mechanism that can be used(intended) to implement different patterns. It is(behavior) generally a flag(possibly protected by mutual exclusion). (One interesting fact is even mutex
pattern can be used to implement semaphore).
In popular culture, semaphores
are mechanisms provided by kernels, and mutexes
are provided by user-space library.
Note, 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 the truth is all the mutexes, semaphores and barriers are used for synchronization. The intent of mutex is not ownership
but mutual exclusion
. This misconception gave the rise of popular interview question asking the difference of the mutexes
and binary-semaphores
.
Summary,
intentIn design perspective, mutex
is more like state-pattern
where the algorithm that is selected by the state can change the state. The binary-semaphore
is more like strategy-pattern
where the external algorithm can change the state and eventually the algorithm/strategy selected to run.
This two articles explain great details about mutex vs semaphores Also this stack overflow answer tells the similar answer.