In literal sense, mutex as the name suggests means mutual exclusion. It is used to take a lock on shared data such as an array or a variable etc.
At any given time, a mutex only allows a single thread to access a resource.
On the other hand, a semaphore is used to give access to a collection of resources to multiple threads. Think of semaphores as the number of parking spots in a parking lot. If the parking lot is full, then a thread requesting a parking spot (access to a resource) remains blocked until an earlier thread takes out the vehicle and empties a parking spot (releases access to a resource).
A semaphore with a single parking spot(single access pass) is called a binary semaphore and is often confused with a mutex. Semaphore can also be used to signal other threads that “Hey I’m leaving now, you can take up the space”. A mutex on the other hand leaves the parking spot without letting the other person know, and only ensures that one parking spot (resource) is accessed by one thread (himself) at any given time.
Semaphore vs Mutex
A semaphore can act as a mutex when it has only one pass to give. (also called binary semaphore). There is a great misconception that a binary semaphore is same as mutex, but
Strictly speaking, a mutex is a locking mechanism used to provide exclusive access to a resource. It implies that only the owner who has the mutex can release the mutex and only then the next guy is allowed to use the resource, or simply put there is ownership given to the thread over the resource via a mutex.
While on the other hand, a semaphore is a kind of signalling mechanism. (“Okay. I’m done, you may carry on now like a waiting queue outside a toilet”)
- Mutex means mutual exclusion and gives exclusive access to a single thread on a resource, whereas semaphore can also be used as mutex along with providing feature of signalling amongst threads.
- The thread with mutex has ownership over the resource while there is no concept of ownership in semaphore.
- Mutex if locked, has to be unlocked by the same thread. A semaphore however can be acted upon by different threads.