Implementing a Monitor Using Semaphores

Implementation of the monitor mechanism using semaphores. For each monitor, a semaphore mutex (initialized to 1) is provided. A process must execute wait(mutex) 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. The signaling processes can use next 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

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–;
}

Leave a Comment