How to implement monitors using semaphores?


To implement monitor using semaphores, for each monitor, a semaphore mutex (which is initialized to 1) is provided. Wait(mutex) must be executed by a process before entering the monitor and must execute signal(mutex) after leaving the monitor. Since a signaling process must wait until the resumed process either leaves or waits, an additional semaphore, next, is introduced, initialized to 0. next can be used by The signaling processes to suspend themselves. An integer variable next_count is also provided to count the number of processes suspended on next. Thus, each external function F is replaced by-

wait(mutex);
…
body of F
...
if (next_count > 0)
   signal(next);
else
   signal(mutex);

Mutual exclusion within a monitor is ensured. Let’s now see how condition variables are implemented as well. For each condition x, we introduce a semaphore x _sem and an integer variable x_count, both initialized to 0. The operation x.wait() can now be implemented as −

x_count++;
if (next_count > 0){
   signal(next);
}
   else {
   signal(mutex);
}
wait(x_sem);
x_count--;

The operation x.signal() can be implemented as −

if (x _count > 0){
   next_count++;
   signal(x_sem);
   wait(next);
   next_count--;
}

Updated on: 11-Oct-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements