//
The Producer-Consumer Problem (also called the Bounded Buffer Problem) is one of the most fundamental synchronization problems in operating systems.
Two types of processes share a fixed-size buffer:
Three semaphores are needed:
mutex (Binary Semaphore, init = 1): Ensures mutual exclusion when accessing the buffer.empty (Counting Semaphore, init = N): Tracks the number of empty slots in the buffer. Producer waits if this is 0.full (Counting Semaphore, init = 0): Tracks the number of filled slots. Consumer waits if this is 0.while (true) {
item = produce();
wait(empty); // Decrement empty count; block if buffer full
wait(mutex); // Enter critical section
buffer[in] = item;
in = (in + 1) % N;
signal(mutex); // Exit critical section
signal(full); // Increment full count; wake consumer
}
while (true) {
wait(full); // Decrement full count; block if buffer empty
wait(mutex); // Enter critical section
item = buffer[out];
out = (out + 1) % N;
signal(mutex); // Exit critical section
signal(empty); // Increment empty count; wake producer
consume(item);
}
If the order of wait(empty) and wait(mutex) is swapped in the Producer, a deadlock can occur. The Producer acquires the mutex, then finds the buffer full and blocks on wait(empty). But the Consumer can never acquire the mutex to consume an item and signal empty, because the Producer holds it. Both processes are permanently stuck.