What it is
A bounded buffer is a fixed capacity ring queue shared between producers and consumers. Unlike an unbounded queue it applies backpressure, blocking producers when full so memory use stays predictable.
The two semaphore trick
The elegant implementation uses two counting semaphores plus a mutex:
- empty is initialised to the capacity and counts free slots.
- full is initialised to zero and counts occupied slots.
- A producer waits on empty, locks, inserts, unlocks, then posts full.
- A consumer waits on full, locks, removes, unlocks, then posts empty.
Why the order matters
The semaphore wait must come before the mutex lock. If you lock first and then wait on a full buffer you hold the mutex while blocked, and no consumer can ever make space. This is a deadlock caused by acquiring resources in the wrong order.
The buffer guarantees that at most capacity items exist at once, giving the system natural flow control.
Key idea
A bounded buffer uses empty and full counting semaphores around a mutex to apply backpressure, and waiting before locking avoids deadlock.