operating-systems concurrency

Definition

Producer-Consumer Problem

The producer-consumer problem (bounded-buffer problem) is a classic synchronisation problem where producers generate data into a shared fixed-size buffer, and consumers retrieve and process it.

Requirements

Mutual Exclusion

Only one process (producer or consumer) may access the buffer at any time to prevent data corruption.

Condition Synchronisation

  • Producer waits if buffer is full
  • Consumer waits if buffer is empty

Implementation

Semaphore Solution

Uses three semaphores:

// Producer
while (true) {
    produce(item);
    wait(E);        // Wait for empty slot
    wait(S);        // Enter critical section
    append(item);
    signal(S);      // Leave critical section
    signal(N);      // Increment item count
}
// Consumer
while (true) {
    wait(N);        // Wait for item
    wait(S);        // Enter critical section
    item = take();
    signal(S);      // Leave critical section
    signal(E);      // Increment empty count
    consume(item);
}

Deadlock Risk

Order of wait operations is critical. Acquiring mutex S before checking condition semaphores (N or E) can cause deadlock if buffer is empty/full.