Semaphore And Mutex

Semaphore and Mutex.

Mutexes, monitors and semaphores are all synchronization mechanisms i.e. they are used to mediate access to a shared resource between multiple processes or threads (referred to as processes henceforth). However, they are used differently:


Used to provide mutual exclusion i.e. ensures at most one process can do something (like execute a section of code, or access a variable) at a time. A famous analogy is the bathroom key in a Starbucks; only one person can acquire it, therefore only that one person may enter and use the bathroom. Everybody else who wants to use the bathroom has to wait till the key is available again.


Provides mutual exclusion to an object i.e. at any point in time, at most one process may access any of the object's members/ execute any of its methods. This is ideologically similar to a mutex for an entire OOP instance*; no part of the instance can be touched by more than one process at a time.


Is a counter which grants count number**of accesses to a resource at a time. So if a semaphore has initial count = 5, the resource it protects may be accessed by at most 5 requestors*** at a time; the 6th requestor onwards will have to wait for an empty 'slot'. Think of a patient's hospital room that has 5 seats; the nurse allows visitors to enter until all 5 seats are occupied. Any other visitors must wait outside until a seat becomes vacant, at which point the nurse allows one to enter. Semaphores are typically used as a signaling mechanism between processes. A typical example is a producer-consumer process pair (not explained here to keep the answer to a readable length).