In: Computer Science
What are Semaphores and Mutex? What are they used for?
SEMAPHORE
Semaphore is simply a variable that is non-negative and shared between processes. A semaphore is a signaling mechanism, and a process that is waiting on a semaphore, can be signaled by another process so that at a time only one process can enter into critical section (shared resource) so that we can have mutual exclusion.
It uses two atomic operations:
1) Wait(P): decrement the value of semaphore
2) Signal(V): Increment the value of semaphore.
It is of two types :
1) Binary Semaphore: In this, semaphore have 0 and 1 value. 0 (zero) is when wait operation is used and 1 is when signal operation is used. Initially value of S is 1.
2) Counting Semaphore: In this, semaphore have non-negative integers (for eg: 0,1,2,3..) as a value.
Use of Semaphore
MUTEX
Use of Mutex
A mutex provides mutual exclusion, which can be either producer or consumer that can have the key (mutex) and proceed with their work. As long as producer fills buffer, the user needs to wait, and vice versa. In Mutex lock, all the time, only a single thread can work with the entire buffer.