The following is a code with two threads, producer and consumer, that can run…

2008

The following is a code with two threads, producer and consumer, that can run in parallel. Further, S and Q are binary semaphores equipped with the standard P and V operations.

semaphore S = 1, Q = 0; 
integer x;

producer:                   consumer:
while (true) do             while (true) do
    P(S);                       P(Q);
    x = produce ();             consume (x);
    V(Q);                       V(S);
done                        done

Which of the following is TRUE about the program above?

  1. A.

    The process can deadlock

  2. B.

    One of the threads can starve

  3. C.

    Some of the items produced by the producer may be lost

  4. D.

    Values generated and stored in 'x' by the producer will always be consumed before the producer can generate a new value

Attempted by 105 students.

Show answer & explanation

Correct answer: D

Correct conclusion: Values generated and stored in 'x' by the producer will always be consumed before the producer can generate a new value.

Reasoning:

  • Initial semaphore values: S = 1 (used to control access to the shared variable x), Q = 0 (counts produced items).

  • Producer sequence: P(S) -> x = produce() -> V(Q). The producer acquires S before writing x and signals Q after producing.

  • Consumer sequence: P(Q) -> consume(x) -> V(S). The consumer waits for an available item via Q, consumes x, then releases S.

  • Because the producer must hold S to produce and the consumer only releases S after consuming, the producer cannot produce a new value until the consumer has consumed the previous one and released S.

  • As a result, no produced value stored in x can be overwritten or lost before being consumed, and there is no deadlock or starvation in the intended behavior (assuming standard semaphore wake semantics).

A video solution is available for this question — log in and enroll to watch it.

Explore the full course: Gate Guidance By Sanchit Sir