GATE 2018 CS – Question 50
Consider the following solution to the producer-consumer synchronization problem. The shared buffer size is $N$. Three semaphores $empty$, $full$ and $mutex$ are defined with respective initial values of 0, $N$ and 1. Semaphore $empty$ denotes the number of available slots in the buffer, for the consumer to read from. Semaphore $full$ denotes the number of available slots in the buffer, for the producer to write to. The placeholder variables, denoted by P, Q, R, and S, in the code below can be assigned either $empty$ or $full$. The valid semaphore operations are: `wait()` and `signal()`.
Producer: Consumer:
do{ do{
wait(P); wait(R);
wait(mutex); wait(mutex);
//Add item to buffer //Consume item from buffer
signal(mutex); signal(mutex);
signal(Q); signal(S);
}while(1); }while(1);Which one of the following assignments to P, Q, R and S will yield the correct solution?
Practise this question in The GATE Grind →
Show answer and explanation
Correct answer: (C) P: full, Q: empty, R: empty, S: full
Explanation
Here $full$ (initially $N$) counts free slots for the producer and $empty$ (initially 0) counts items for the consumer. The producer waits on $full$ (P) and afterwards signals $empty$ (Q). The consumer waits on $empty$ (R) and afterwards signals $full$ (S). So P: full, Q: empty, R: empty, S: full.