KatInterview

Blocking Bounded Buffer for Many Producers and Consumers

Data Structure DesignModel answer
HardModel answerData Structure Designconcurrencysynchronizationcondition-variables

Last updated

Design and code a fixed-capacity, multi-producer multi-consumer buffer with timed blocking put/get, fair waiter ordering, clean shutdown and backpressure, and explain how you would test it.

Build an in-memory buffer that many threads can share. Any number of producer threads add items and any number of consumer threads remove them. The buffer holds at most capacity items, fixed at construction.

Required behavior

  • put(item, timeout=None) blocks while the buffer is full. get(timeout=None) blocks while it is empty.
  • A timeout of None waits indefinitely, 0 means "try once without blocking", and a positive value is a deadline in seconds. When the deadline passes, the call raises a timeout error.
  • Items must come out in the same order they went in.
  • Threads must not deadlock, and no thread should wait forever while others keep getting served. Waiting producers should be served in arrival order, and so should waiting consumers.
  • Provide a way to shut the buffer down. After shutdown, new put calls fail, get still drains the remaining items and then fails, and every blocked thread wakes up.

What to cover in your answer

  1. Your locking strategy and why you chose it over the alternatives (a single mutex, separate locks for the two ends, lock-free).
  2. How threads are signaled, and how you avoid lost wakeups and wake-everyone stampedes.
  3. What happens when the buffer is full (backpressure), and what choices you give callers.
  4. A working implementation.
  5. Time and space complexity.
  6. How you would test correctness and measure performance.

Hints

Hint 1

Start with one lock guarding a deque and get it correct. Only then ask what changes for fairness, and which parts of a lock-free design would still need a blocking mechanism.

Hint 2

Fairness needs more than a shared condition variable. Keep an explicit FIFO line of waiters for each role, give each waiter its own condition, and let a thread proceed only if it is at the front and the state allows it. Make new arrivals skip the fast path when someone is already waiting.

Hint 3

Every way of leaving a wait (success, timeout, shutdown) must pass the baton: after you leave the line, re-check whether the new front waiter can now proceed and notify it. Compute a single absolute deadline up front so spurious wakeups do not extend the wait.