← Lessons

quiz vs the machine

Gold1340

Concurrency

The Bounded Buffer

A fixed size queue with two counting semaphores that never overflows or underflows.

5 min read · core · beat Gold to climb

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.

Check yourself

Answer to earn rating on the learn ladder.

1. What does the empty semaphore count?

2. Why must the semaphore wait precede the mutex lock?