Build a Shutdown-Aware Producer/Consumer Queue in C++
Data Structure DesignModel answerLast 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 intoout_value.- Returns
trueif an item was delivered. - Returns
falseonly when the queue has been shut down and has no items left.
- Returns
void shutdown(): declares that no further items will be added, and wakes every thread currently blocked inpop.
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_variableandstd::queue. Tis 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
- The shared state and how it is protected.
- The code for all three operations.
- Why it has no lost wakeups and tolerates spurious wakeups.
- How exceptions are handled in
pushandpop. - Your policy for items left in the queue at shutdown, for
pushafter shutdown, and for destruction. - 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The queue has three pieces of shared state, all guarded by one mutex:
std::queue<T> q_: the buffered items.bool shutdown_: set once producers are finished.std::condition_variable cv_: lets consumers sleep until the condition "an item exists or shutdown was requested" holds.
The key design rule is that consumers wait on a predicate, not on a bare notification. After waking, a consumer inspects the state:
- Queue non-empty: take the front item and return
true. This applies even after shutdown, so the queue drains before consumers are told to stop. - Queue empty (which means shutdown is set): return
false.
Code
#include <condition_variable>
#include <mutex>
#include <queue>
#include <stdexcept>
#include <utility>
template <typename T>
class BlockingQueue {
public:
BlockingQueue() = default;
BlockingQueue(const BlockingQueue&) = delete;
BlockingQueue& operator=(const BlockingQueue&) = delete;
void push(T value) { // by value: copy happens before locking
{
std::lock_guard<std::mutex> lock(mtx_);
if (shutdown_) {
throw std::runtime_error("push after shutdown");
}
q_.push(std::move(value));
}
cv_.notify_one(); // one new item can satisfy one consumer
}
bool pop(T& out_value) {
std::unique_lock<std::mutex> lock(mtx_);
cv_.wait(lock, [this] { return !q_.empty() || shutdown_; });
if (q_.empty()) {
return false; // shut down and fully drained
}
out_value = std::move(q_.front()); // may throw: item is still queued
q_.pop();
return true;
}
void shutdown() {
{
std::lock_guard<std::mutex> lock(mtx_);
shutdown_ = true; // idempotent
}
cv_.notify_all(); // wake every sleeper
}
private:
std::mutex mtx_;
std::condition_variable cv_;
std::queue<T> q_;
bool shutdown_ = false;
};
Why it is correct
- No data races. Every access to
q_andshutdown_happens while holdingmtx_. - Spurious wakeups. The predicate overload of
waitre-checks the condition in a loop, so a thread only proceeds when the condition genuinely holds. - No lost wakeups. The predicate is evaluated under the lock, and
waitatomically releases the lock and blocks. Because state changes also happen under the lock, a change cannot slip in between a consumer's check and its sleep. This is also whyshutdown_must be written under the mutex even though it is a plainbool. Making it a bare atomic written outside the lock can reintroduce the lost-wakeup race: the flag flips and the notification fires after the consumer's check but before it sleeps. - Many consumers at shutdown.
notify_onewould wake a single consumer and could leave the rest asleep forever.notify_allwakes all of them. Each reacquires the lock in turn, takes any remaining items, and once the queue is empty they all observeempty && shutdown_and returnfalse. notify_oneinpush. One item satisfies at most one consumer. Notifying after the lock is released avoids waking a thread that would instantly block on the mutex.
Exception safety
push: the by-value parameter moves any copying outside the critical section.std::queueis backed bystd::deque, whosepush_backgives the strong guarantee, so a throwing allocation or move leaves the queue unchanged.lock_guardreleases the mutex during unwinding.pop: we assign intoout_valuebefore removing the element. If the assignment throws, the item is still at the front and nothing is lost. This is why the API uses an out-parameter rather thanT pop(): returning by value would require removing the element first and then copying it out, and a throw at that point would destroy the item. It is the same reasoning behind thetop()/pop()split instd::stack.shutdown: only sets a flag and notifies, so it effectively cannot throw.
Complexity
push: O(1) amortized.pop: O(1) once woken; the waiting time depends on producers.- Space: O(n) for n queued items.
- All operations serialize on one mutex, so throughput under heavy contention is bounded by that lock.
Policy decisions to state explicitly
- Drain vs abort. Here consumers still receive queued items after shutdown, and
falseonly appears once the queue is empty. For abort semantics, clear the queue insideshutdown(). pushafter shutdown. It is a contract violation, so this version throws. Returningbool, or silently discarding the item, are defensible alternatives, but you should choose one and say so.- Repeated
shutdown()is harmless. - Destruction. Destroying the queue while threads are blocked in it is undefined behavior. The owner must call
shutdown()and join consumers first. - Timeouts. A plain
popon an empty, live queue blocks forever. Atry_popor apop_for(timeout)built onwait_foris a natural addition.
Common mistakes
- Using
ifinstead of a predicate or loop aroundwait, which breaks on spurious wakeups. - Calling
notify_oneinshutdown, stranding some consumers. - Setting the shutdown flag without holding the mutex.
- Returning
falseas soon as shutdown is set, even though items remain, which silently drops data. - Returning
Tby value frompop, losing exception safety.
Follow-ups
Bounded capacity. Add capacity_ and a second condition variable not_full_. push waits on q_.size() < capacity_ || shutdown_ and returns bool (false if shut down). After each successful pop, call not_full_.notify_one(). shutdown() must notify_all on both condition variables so blocked producers are released. Two condition variables avoid waking the wrong side. A fixed-size ring buffer avoids allocation on the hot path.
Contention. One mutex means producers and consumers serialize, its cache line bounces between cores, and blocked threads fall into kernel waits that cost microseconds. Options:
- Batching: a consumer swaps the whole internal queue into a local one under the lock, then processes it without the lock.
- Two-lock queue (Michael-Scott): a linked list with separate head and tail locks, so pushes and pops rarely contend.
- Lock-free designs: for example an SPSC ring buffer using acquire/release atomics, trading simplicity and blocking behavior for lower latency. These need care around memory ordering and a separate strategy for sleeping when empty.