StreakPeaked· Practice

ExamsGATETechnical

Consider the procedure below for the Producer-Consumer problem which uses semaphores: semaphore $n = 0$; semaphore $s = 1$; void producer() { while(true) { produce(); semWait(s); addToBuffer(); semSignal(s); semSignal(n); } } void consumer() { while(true) { semWait(s); semWait(n); removeFromBuffer(); semSignal(s); consume(); } } Which one of the following is TRUE?

  1. The producer will be able to add an item to the buffer, but the consumer can never consume it.
  2. The consumer will remove no more than one item from the buffer.
  3. Deadlock occurs if the consumer succeeds in acquiring semaphore s when the buffer is empty.
  4. The starting value for the semaphore n must be 1 and not 0 for deadlock-free operation.

Correct answer: The producer will be able to add an item to the buffer, but the consumer can never consume it.

Solution

The consumer first acquires the mutex semaphore `s` and then waits on `n`. If `n=0`, the consumer blocks while still holding `s`, preventing the producer from entering the critical section to add an item. Thus the producer can add at most one item only if it gets the mutex first; otherwise the system can deadlock and the consumer cannot consume the item.

Related GATE Technical questions

⚔️ Practice GATE Technical free + battle 1v1 →