Question

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
Official answer and solution
Official answer
C
From
Official GATE 2014 answer key

Solution

Trace semaphore acquisitions in producer and consumer to check for inversion of wait operations leading to deadlock.

  1. Semaphore Roles:

    • Semaphore ss (initialized to 1) provides mutual exclusion on the shared buffer.
    • Semaphore nn (initialized to 0) counts the number of available items in the buffer.
  2. Consumer Execution Order:

    • In the consumer code:
      semWait(s); // acquires mutual exclusion lock
      semWait(n); // waits for an item to become available
      
  3. Deadlock Scenario:

    • Suppose the buffer is initially empty (n=0n = 0) and the consumer executes first.
    • The consumer calls semWait(s), successfully decrementing ss from 1 to 0 and acquiring the lock.
    • The consumer next calls semWait(n). Because n=0n = 0, the consumer is put to sleep waiting for an item.
    • However, the consumer still holds semaphore s=0s = 0.
    • When the producer later attempts to add an item, its first instruction is semWait(s). Since s=0s = 0, the producer blocks waiting for ss.
    • Both processes are now permanently blocked waiting for each other, creating a classic deadlock.
  4. Conclusion:
    Deadlock occurs if the consumer succeeds in acquiring semaphore ss when the buffer is empty, matching option (C).

Final answer

C

Common trap

Overlooking that holding the mutual exclusion semaphore s while blocking on resource semaphore n prevents the producer from ever generating the resource.

The answer is the one in the official GATE answer key. The solution is this site's own explanation.

Source

Paper
GATE 2014 Computer Science and Information Technology (CS) Session 2
Question
41 of 65, printed as CS Q.31
Section
Computer Science and Information Technology

Report an error in this question

GATE questions are the work of the organising institutes. This site is independent and is not affiliated with them.