In: Computer Science
Compare and contrast the three techniques of dealing with critical sections of code in (1) busy-wait, (2) mutex, and (3) semaphore.
QUESTION
Compare and contrast the three techniques of dealing with critical sections of code in (1) busy-wait, (2) mutex, and (3) semaphore.
SOLUTION
Critical Section
A section of code in which only 1 process can be executed at any given time because it uses shared variables. We can use different techniques to solve this problem.
(1) Busy Wait
The repeated execution of a loop of code while waiting for an event to occur is called busy waiting. The CPU is not engaged in any real productive activity during this period, and the process does not progress toward completion.In view of critical section, busy waiting means while it is waiting to enter its critical section it does nothing but continue to test its entry condition.If a low priority process is in its critical section, and a high priority process goes into busy waiting, it may never get to its critical section.
(2) Mutex
Mutex is a mutual exclusion object that synchronizes access to a resource. It is created with a unique name at the start of a program. The Mutex is a locking mechanism that makes sure only one thread can acquire the Mutex at a time and enter the critical section.
Example:
wait (mutex);
…..
Critical Section
…..
signal (mutex);
(3)Semaphore
A semaphore is a signalling mechanism and a thread that is waiting on a semaphore can be signaled by another thread. A semaphore uses two atomic operations, wait and signal for process synchronization.
The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed.
Example:
wait(S)
{
while (S<=0);
S--;
}
The signal
operation increments the value of its argument S.
Example:
signal(S)
{
S++;
}
There are mainly two types of semaphores i.e. counting semaphores and binary semaphores.
Counting Semaphores are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources.
The binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0.
Conclusion
Difference between Mutex and Semaphore
Both busy waiting and blocking methods can be used as means to address critical section problems and process synchronization.On a single CPU, busy waiting becomes a circular issue, so blocking would make more sense.
Mutex and Semaphores are examples of blocking methods.
A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. Semaphore is different from mutex as the mutex can be signaled only by the thread that called the wait function.Also binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.