Skip to content
We areTOP 1%

Explain the producer-consumer problem and its semaphore solution.

MediumConceptProcess Synchronization
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

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)
  • empty and full count slots and make threads wait; mutex only protects the buffer itself.
  • The order matters: if a producer called wait(mutex) before wait(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.

More in Process Synchronization

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account