Explain the producer-consumer problem and its semaphore solution.
MediumConceptProcess Synchronization
Answer
In the producer-consumer (bounded-buffer) problem, producers put items into a shared buffer that holds N items and consumers take them out. A producer must wait when the buffer is full, a consumer must wait when it is empty, and only one thread may change the buffer at a time. The standard solution uses three semaphores: empty = N (free slots), full = 0 (filled slots) and mutex = 1 (a lock on the buffer).
Producer Consumer
wait(empty) wait(full)
wait(mutex) wait(mutex)
add item remove item
signal(mutex) signal(mutex)
signal(full) signal(empty)
emptyandfullcount slots and make threads wait;mutexonly protects the buffer itself.- The order matters: if a producer called
wait(mutex)beforewait(empty)on a full buffer, it would sleep while holding the lock, no consumer could get in, and the system would deadlock.
Example: N = 2. The producer adds two items (empty 2 → 0, full 0 → 2), and its third wait(empty) blocks. A consumer removes one item (full 2 → 1), and its signal(empty) (0 → 1) wakes the producer. A print queue between applications and a printer works the same way.