The wait and signal operations of a monitor are implemented using semaphores…

2006

The wait and signal operations of a monitor are implemented using semaphores as follows. In the following, 

  • x is a condition variable,

  • mutex is a semaphore initialized to 1,

  • x_sem is a semaphore initialized to 0,

  • x_count is the number of processes waiting on semaphore x_sem, initially 0, next is a semaphore initialized to 0,

  • next_count is the number of processes waiting on semaphore next, initially 0.

P(mutex); 
body of procedure 
if (next_count > 0) 
    V(next); 
else
    V(mutex); 

Each occurrence of x.wait is replaced with the following:

x_count = x_count + 1; 
if (next_count > 0) 
    V(next) 
else
    V(mutex); 
---------------------------------- E1; 
x_count = x_count - 1; 

Each occurrence of x.signal is replaced with the following:

if (x_count > 0) 
{ 
    next_count = next_count + 1; 
 ---------------------------------- E2; 
    P(next), 
    next_count = next_count - 1; 
} 

For correct implementation of the monitor, statements E1 and E2 are, respectively,

  1. A.

    P(x_sem), V(next)

  2. B.

    V(next), P(x_sem)

  3. C.

    P(next), V(x_sem)

  4. D.

    P(x_sem), V(x_sem)

Attempted by 55 students.

Show answer & explanation

Correct answer: D

Answer: E1 = P(x_sem), E2 = V(x_sem)

Reasoning:

  • Wait (E1): After the waiting thread increments x_count and releases the monitor lock (via V(next) or V(mutex) as appropriate), it must block until a signal occurs. The correct semaphore to block on is the condition semaphore x_sem, so the waiting thread performs P(x_sem). After P(x_sem) returns it decrements x_count and resumes inside the monitor.

  • Signal (E2): If there is at least one waiting thread (x_count > 0), the signaling thread must wake one waiting thread by performing V(x_sem). To ensure correct handoff of the monitor, the signaling thread increments next_count, performs V(x_sem) to wake the waiter, and then waits on next (P(next)) so the awakened thread can take over; when the awakened thread finishes its use of the monitor it will V(next) to allow the signaling thread to continue. Thus E2 is V(x_sem).

  • Summary: The waiting side must perform P(x_sem) to block on the condition variable; the signaling side must perform V(x_sem) to wake a waiter. The next/next_count semaphores manage the monitor handoff and are used in addition to these operations but do not replace the need to V(x_sem) when signaling.

Explore the full course: Gate Guidance By Sanchit Sir