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:
empty– Counts available empty slots (initialized to buffer size N)full– Counts filled slots waiting to be consumed (initialized to 0)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?
emptyandfullenforce the bounded-buffer constraint (capacity limits)mutexprevents race conditions when modifying buffer pointers/data- Order matters: always acquire resource semaphores (
empty/full) beforemutexto 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.