Implementing Monitor using Semaphore
Let’s implement a a monitor mechanism using semaphores.
Following is a step-by-step implementation:
Step 1: Initialize a semaphore mutex to 1.
Step 2: Provide a semaphore mutex for each monitor.
Step 3: A process must execute wait (mutex) before entering the monitor and must execute signal (mutex) after leaving the monitor.
Step 4: Since a signaling process must wait until the resumed process either leaves or waits, introduce an additional semaphore, S, and initialize it to 0.
Step 5: The signaling processes can use S to suspend themselves. An integer variable S_count is also provided to count the number of processes suspended next. Thus, each external function Fun is replaced by
wait (mutex);
body of Fun
if (S_count > 0)
signal (S);
else
signal (mutex);
Mutual exclusion within a monitor is ensured.
Let’s see how condition variables are implemented.
Step 1: x is condition.
Step 2: Introduce a semaphore x_num and an integer variable x_count.
Step 3: Initialize both semaphores to 0.
x.wait() is now implemented as: x.wait()
x_count++;
if (S_count > 0)
signal (S);
else
signal (mutex);
wait (x_num);
x_count–;
The operation x.signal () can be implemented as
if (x_count > 0) {
S_count++;
signal (x_num);
wait (S);
S_count–;
}
Implementing Monitor using Semaphore
When multiple processes run at the same time and share system resources, the results may be different. This is called a critical section problem. To overcome this problem we can implement many solutions. The monitor mechanism is the compiler-type solution to avoid critical section problems. In this section, we will see how to implement a monitor using semaphore.