Course contentsShow
← Computer Science
Lesson 1298 of 2,87230. Process SynchronizationFree lesson

Producer-Consumer Problem with Semaphores

Solving the bounded-buffer producer-consumer problem using empty, full, and mutex semaphores.

Producer-Consumer Problem with Semaphores

What You'll Learn

You'll learn how to use empty, full, and mutex semaphores together to safely coordinate producers and consumers sharing a bounded buffer.

The Bounded-Buffer Challenge

The producer-consumer problem (also called the bounded-buffer problem) involves two types of threads:

  • Producers generate data and place it into a fixed-size buffer
  • Consumers remove data from that buffer and process it

The buffer has limited slots—producers must wait when it's full, consumers must wait when it's empty, and only one thread should modify the buffer at a time.

Three-Semaphore Solution

This classic problem requires three counting semaphores working in harmony:

  1. empty – Counts available empty slots (initialized to buffer size N)
  2. full – Counts filled slots waiting to be consumed (initialized to 0)
  3. mutex – Binary semaphore ensuring mutual exclusion for buffer access (initialized to 1)

Producer Pattern

wait(empty);      // Ensure space available
wait(mutex);      // Enter critical section
// Add item to buffer
signal(mutex);    // Exit critical section
signal(full);     // Signal one more item available

Consumer Pattern

wait(full);       // Ensure item available
wait(mutex);      // Enter critical section
// Remove item from buffer
signal(mutex);    // Exit critical section
signal(empty);    // Signal one more space available

Why All Three?

  • empty and full enforce the bounded-buffer constraint (capacity limits)
  • mutex prevents race conditions when modifying buffer pointers/data
  • Order matters: always acquire resource semaphores (empty/full) before mutex to avoid deadlock

Key Takeaway: The producer-consumer problem requires three semaphores: empty and full to track buffer capacity, and mutex to protect critical sections where the buffer is actually modified.