KatInterview

Build a Shutdown-Aware Producer/Consumer Queue in C++

Data Structure DesignModel answer
MediumModel answerData Structure Designcppconcurrencymutex

Last updated

Design a generic, thread-safe C++ queue where consumers block when it is empty and a shutdown call releases every waiting thread once the remaining items are drained.

Task

Write a C++ class template, BlockingQueue<T>, that lets several producer threads and several consumer threads exchange items safely.

A consumer that asks for an item while the queue is empty must sleep until an item shows up. The queue must also support a shutdown signal, so that consumers sleeping on an empty queue are released and told that nothing more will ever arrive.

Required interface

  • void push(T value): enqueue an item.
  • bool pop(T& out_value): dequeue an item into out_value.
    • Returns true if an item was delivered.
    • Returns false only when the queue has been shut down and has no items left.
  • void shutdown(): declares that no further items will be added, and wakes every thread currently blocked in pop.

The implementation must be free of data races and exception-safe.

Illustration

BlockingQueue<int> q;

// Thread A
q.push(42);

// Thread B
int v;
if (q.pop(v)) {
    // blocks until A pushes; then v == 42
}

// Thread C
q.shutdown();   // any pop() still blocked on an empty queue returns false

Constraints

  • Build it from std::mutex, std::condition_variable and std::queue.
  • T is copyable or movable.
  • Think carefully about what happens when many consumers are blocked at the moment shutdown() is called.

What to cover in your answer

  1. The shared state and how it is protected.
  2. The code for all three operations.
  3. Why it has no lost wakeups and tolerates spurious wakeups.
  4. How exceptions are handled in push and pop.
  5. Your policy for items left in the queue at shutdown, for push after shutdown, and for destruction.
  6. How you would extend it (bounded capacity, reducing contention).

Hints

Hint 1

Three pieces of state are shared: the container, a shutdown flag, and a condition variable. Decide which mutex guards each of them before writing any code.

Hint 2

A consumer should not wait for 'a notification'. It should wait for a condition: the queue is non-empty OR shutdown has been requested. Use the predicate form of wait, and decide what to do after waking based on which part of the condition is true.

Hint 3

Think about what shutdown means for items still queued: should consumers get them first, or be cut off? Also ask whether notify_one or notify_all is right in shutdown, and why the flag must be written under the lock.

Hint 4

Consider why returning T by value from pop is awkward for exception safety, and how an out-parameter plus 'assign first, remove second' avoids losing an element.