Mutex vs Semaphore
Mutex are used to provide serialized access to a part of a re-entrant code that cannot be executed in parallel by more than one thread. A mutex makes sure that only one code can access the controlled section at a time. To gain access, other codes are made to wait until the first code exits. You can consider it to be like a key to a room. The person having access to that key first goes first. Until the time the person returns back, nobody else can access that room.
Semaphore gives access to a shared resource to a number of users simultaneously. As the number of users accessing the resource increases, the semaphore count reduces. Once the users start releasing the resource, the semaphore count starts rising again. It is used by applications that require synchronization. The number of concurrent users is restricted based on the semaphore limit. A semaphore can be thought of as a bunch of similar keys to similar locks to a single room, but these keys are limited in number. People who have these keys can share the room.
Differences between mutex and semaphore:
1. Mutex is used for mutual exclusion whereas semaphore finds its utility in both event
notification and mutual exclusions.
2. Mutex provides serial access to common resources whereas semaphore puts a limit to
the number of concurrent accesses.
3. A mutex works with one thread at a time while semaphore manages multiple threads
together.
4. Mutex has a concept of an owner where the process that locks the mutex can only
reopen it. None of the other processes can do so. But in the case of semaphore, such
restrictions do not exist.
5. A mutex is a locking mechanism whereas a semaphore is a signaling mechanism with
respect to synchronizing access to a resource.
Summary:
1. Semantically and in theory, both mutex and semaphore are the same. One can be
implemented using the other, but practically both are different.
2. A mutex is nothing but a semaphore with a count value equal to one.
3. A mutex is a semaphore with additional features like ownership and priority inversion
protection.
4. A semaphore is an abstract data type that controls access to a common resource by
multiple processes in a parallel programming environment.
5. Semaphore finds its use in many operating systems as synchronization primitive.
6. Both mutex and semaphore are kernel resources that are used for the purpose of
synchronization.