Skip to content
Official PYQ · 2014

GATE CS 2014 Set 2 Q31 — Concurrency and Synchronization

Explain with AI

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?

Choose one option
View worked solution

Answer: C

To analyze the behavior of the given Producer-Consumer implementation, let us look at the semaphores used:

  • s = 1: A binary semaphore (mutex) used to ensure mutual exclusion when accessing the shared buffer.
  • n = 0: A counting semaphore representing the number of items currently in the buffer.

Deadlock Analysis

Consider the scenario where the buffer is initially empty (n=0n = 0) and the consumer process executes first:

  1. The consumer executes semWait(s). Since s=1s = 1, the consumer successfully acquires the mutex, and ss becomes 00.
  2. The consumer then executes semWait(n). Since the buffer is empty (n=0n = 0), the consumer is blocked on semaphore nn. Crucially, the consumer is still holding the mutex ss.
  3. The producer process now attempts to run. It executes produce() and then calls semWait(s).
  4. Since s=0s = 0 (held by the consumer), the producer blocks on semaphore ss.

At this point:

  • The consumer is waiting for the producer to signal nn (via semSignal(n)).
  • The producer is waiting for the consumer to release ss (via semSignal(s)).

This circular wait results in a deadlock.

Evaluating the Options

  • Option A is incorrect: If the producer runs first, it successfully adds an item and signals nn. The consumer can then successfully consume it.
  • Option B is incorrect: If the producer continuously produces items ahead of the consumer, the consumer can remove multiple items without deadlocking, as long as the buffer never becomes empty when the consumer acquires ss.
  • Option C is correct: As demonstrated in our trace, if the consumer acquires ss when the buffer is empty (n=0n = 0), a deadlock occurs.
  • Option D is incorrect: Simply changing the initial value of nn to 11 does not prevent deadlock. The correct solution is to swap the order of the wait operations in the consumer to:
    semWait(n);
    semWait(s);

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Concurrency and Synchronization questions