The semaphore variables full, empty and mutex are initialized to 0, n and 1,…

2004

The semaphore variables full, empty and mutex are initialized to 0, n and 1, respectively. Process P1 repeatedly adds one item at a time to a buffer of size n, and process Prepeatedly removes one item at a time from the same buffer using the programs given below. In the programs, K, L, M and N are unspecified statements.

P1

while (1) {
    K; P(mutex); Add an item to the buffer; V(mutex);     L; } P2 while (1) {    M; P(mutex); Remove an item from the buffer; V(mutex);     N; } The statements K, L, M and N are respectively

  1. A.

    P(full), V(empty), P(full), V(empty)

  2. B.

    P(full), V(empty), P(empty), V(full)

  3. C.

    P(empty), V(full), P(empty), V(full)

  4. D.

    P(empty), V(full), P(full), V(empty)

Attempted by 132 students.

Show answer & explanation

Correct answer: D

Key insight: The producer must wait for an empty slot before adding and signal that a slot is now full after adding; the consumer must wait for a full slot (an available item) before removing and signal that a slot is now empty after removing. Mutex protects the buffer during add/remove.

  1. Producer sequence (what the producer should do):

    • P(empty) — wait for an available slot before entering the critical section.

    • P(mutex) — enter the critical section to safely add the item.

    • Add an item to the buffer.

    • V(mutex) — leave the critical section.

    • V(full) — signal that there is now one more filled slot (an available item for consumers).

  2. Consumer sequence (what the consumer should do):

    • P(full) — wait for an available item before entering the critical section.

    • P(mutex) — enter the critical section to safely remove the item.

    • Remove an item from the buffer.

    • V(mutex) — leave the critical section.

    • V(empty) — signal that there is now one more empty slot (available for producers).

Initialization and final assignment of K, L, M, N:

  • Given full = 0, empty = n, mutex = 1, the correct assignments are:

  • K = P(empty); L = V(full); M = P(full); N = V(empty).

Why other sequences fail (brief):

  • If the producer waits on full (instead of empty), it will block until there is an item present, which prevents production and inverts the intended semantics.

  • If the consumer waits on empty, it will block until there is an empty slot rather than an available item, preventing consumption.

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

Explore the full course: Gate Guidance By Sanchit Sir