Multi-Producer Blocking Queue Template in C++
Medium · Coding & Algorithms · Software Engineer · Onsite
Prompt
Design and implement a generic multi-producer, multi-consumer BlockingQueue<T> class template in modern C++ (std::mutex, std::condition_variable, and std::queue<T>) for any movable or copyable element type T.
Your class template must expose the following public methods:
void push(T value)— Appendsvalueto the back of the queue and notifies a waiting consumer, if any (rejecting pushes once the queue has been shut down).bool pop(T& out_value)— Removes the front element intoout_valueand returnstrue. When the queue is empty and still open, the caller sleeps without busy-waiting until an element arrives or the queue closes. Returnsfalseonce the queue has been shut down and all previously pushed elements have been consumed.void shutdown()— Marks the queue closed to new elements and wakes all blocked consumer threads so none remain stuck waiting.
For example, across concurrent threads:
BlockingQueue<int> tasks;
// Producer thread:
tasks.push(105);
tasks.push(210);
// Consumer thread:
int item = 0;
while (tasks.pop(item)) {
// Processes 105, then 210, then exits once shutdown() is called and the queue is empty
}
// Coordinator thread:
tasks.shutdown();
Scope & Expectations
- Race-free synchronization & wake-ups: Protect all shared queue and shutdown state without data races, lost notifications, or bugs under spurious wake-ups and competing consumers.
- Clean multi-consumer shutdown & draining: Ensure items enqueued prior to
shutdown()are still delivered in FIFO order beforepopreturnsfalseto every waiting consumer. - Exception safety & type-system hygiene: Disable nonsensical copy operations on the queue itself and preserve invariants if copying, moving, or assigning
Tthrows an exception.
Step-by-step walkthrough
Restate the contract and settle edge-case rules
We need a thread-safe C++ class template
BlockingQueue<T>shared by multiple producer and consumer threads:void push(T value): adds one item to the back of the queue.bool pop(T& out_value): removes the oldest item intoout_valueand returnstrue. If the queue is currently empty and still open, the calling thread sleeps until an item arrives or the queue shuts down. Returnsfalseonly when the queue is both shut down and empty.void shutdown(): marks the queue closed to future items and wakes every waiting consumer thread.
Three edge-case rules make this contract airtight:
- Shutdown drains existing work: if 5 items are still in the queue when
shutdown()is called, the next 5popcalls still return those 5 items (true), and only once the queue is empty doespopreturnfalse. That way accepted work is never silently lost. pushaftershutdownthrowsstd::logic_error: sincepushreturnsvoid, throwing is the cleanest way to surface a caller bug instead of silently dropping data.- Copying the queue is disabled (
= delete):std::mutexandstd::condition_variablecannot be copied, and copying a live thread channel has no sensible meaning.
Set up the shared state and the single-mutex invariant
Our class holds four private members:
Producers ---> [ mutex_ ] ---> queue_ (FIFO std::queue<T>) ---> shutdown_ (bool) ---> not_empty_ (std::condition_variable) ---> Consumersstd::mutex mutex_: a mutual-exclusion lock ensuring only one thread inspects or modifies the state at a time.std::condition_variable not_empty_: a waiting room where consumers sleep (consuming zero CPU) whenqueue_is empty.std::queue<T> queue_: the underlying first-in, first-out container (std::deque<T>by default).bool shutdown_ = false: set totrueonceshutdown()is called.
One golden invariant prevents every data race and lost signal: every read and every write of
queue_orshutdown_happens while holdingmutex_. A condition variable never protects data on its own—it simply lets a thread atomically releasemutex_to fall asleep and re-acquiremutex_before waking back up.#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); bool pop(T& out_value); void shutdown(); private: std::mutex mutex_; std::condition_variable not_empty_; std::queue<T> queue_; bool shutdown_ = false; };Implement push with RAII locking and notify_one
In
push(T value), we acquiremutex_usingstd::lock_guard<std::mutex>. This is RAII (Resource Acquisition Is Initialization): the constructor locksmutex_, and the destructor is guaranteed to unlockmutex_whenlockleaves scope—even if an exception is thrown.Taking
valueby value lets callers pass either an lvalue (copied at the call site before locking) or an rvalue/move-only type likestd::unique_ptr<int>(moved in with zero copies), and westd::move(value)intoqueue_. Finally, we callnot_empty_.notify_one()because adding one item can satisfy at most one waiting consumer; waking every consumer would just force the rest to wake up, find the queue empty again, and go right back to sleep.void push(T value) { std::lock_guard<std::mutex> lock(mutex_); if (shutdown_) { throw std::logic_error("Cannot push() after shutdown()"); } queue_.push(std::move(value)); // Wake one sleeping consumer (if any) to claim the new item. not_empty_.notify_one(); }Holding
lockacrossnotify_one()keeps the code compact and avoids a subtle lifetime hazard where another thread pops the final item and destroys theBlockingQueuebeforenotify_one()finishes executing.Implement pop using a predicate wait loop
In
pop(T& out_value), we usestd::unique_lock<std::mutex>instead ofstd::lock_guardbecausenot_empty_.wait(...)needs to unlockmutex_while sleeping and re-lock it upon waking.Never write
if (queue_.empty()) not_empty_.wait(lock);! Always pass a predicate lambda sowaitruns awhileloop internally:Thread C1 calls pop() on empty queue: 1. Locks mutex_, sees queue_.empty() && !shutdown_ 2. wait() atomically unlocks mutex_ and puts C1 to sleep 3. Producer pushes 105 and calls notify_one(), waking C1 4. Suppose Thread C2 sneaks in first, locks mutex_, and pops 105! 5. C1 acquires mutex_ -> wait() RE-CHECKS (!queue_.empty() || shutdown_) -> sees queue_ is empty again -> puts C1 right back to sleep safely!Re-checking the condition in a loop handles both stolen items (another consumer grabbed the item before we re-locked
mutex_) and spurious wake-ups (the operating system occasionally wakes a waiting thread even when nobody callednotify).Once
waitreturns withmutex_locked,!queue_.empty() || shutdown_is guaranteed true:- If
queue_is NOT empty, we move the front element intoout_valuebefore callingqueue_.pop(), and returntrue. IfT's assignment throws an exception, the item has not been popped yet, and we callnot_empty_.notify_one()incatch (...)so another waiting consumer still gets woken for that item! - If
queue_IS empty,shutdown_must betrue, so we returnfalse.
bool pop(T& out_value) { std::unique_lock<std::mutex> lock(mutex_); not_empty_.wait(lock, [this] { return !queue_.empty() || shutdown_; }); // Drain all remaining items first; return false ONLY when shut down AND empty. if (queue_.empty()) { return false; } try { out_value = std::move(queue_.front()); } catch (...) { // Pass the wake-up to another consumer so the unpopped item is not stranded. not_empty_.notify_one(); throw; } queue_.pop(); return true; }- If
Implement shutdown without losing wake-ups
shutdown()setsshutdown_ = trueundermutex_and callsnot_empty_.notify_all():void shutdown() { std::lock_guard<std::mutex> lock(mutex_); shutdown_ = true; // Wake EVERY waiting consumer so none is left sleeping forever. not_empty_.notify_all(); }Two classic bugs happen if you cut corners here:
- Calling
notify_one()instead ofnotify_all(): if 4 consumers are sleeping on an empty queue,notify_one()wakes only 1 consumer (which returnsfalseand exits), leaving the other 3 threads sleeping forever sothread.join()deadlocks! - Updating
shutdown_without lockingmutex_(even ifshutdown_isstd::atomic<bool>!):
Broken timeline when shutdown_ is set WITHOUT mutex_: Consumer: locks mutex_; checks (!queue_.empty() || shutdown_) -> FALSE Shutdown: sets shutdown_ = true; calls notify_all() <-- fires into thin air! Consumer: enters wait() -> unlocks mutex_ and goes to sleep FOREVERBecause
Consumerholdsmutex_continuously from checking the predicate untilwait()atomically puts it on the sleep queue, lockingmutex_insideshutdown()makes it impossible fornotify_all()to slip into that gap.- Calling
Assemble the complete BlockingQueue<T> template
Here is the complete, self-contained C++11 class template:
#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) { std::lock_guard<std::mutex> lock(mutex_); if (shutdown_) { throw std::logic_error("Cannot push() after shutdown()"); } queue_.push(std::move(value)); // Wake one sleeping consumer (if any) to claim the new item. not_empty_.notify_one(); } bool pop(T& out_value) { std::unique_lock<std::mutex> lock(mutex_); not_empty_.wait(lock, [this] { return !queue_.empty() || shutdown_; }); // Drain all remaining items first; return false ONLY when shut down AND empty. if (queue_.empty()) { return false; } try { out_value = std::move(queue_.front()); } catch (...) { // Pass the wake-up to another consumer so the unpopped item is not stranded. not_empty_.notify_one(); throw; } queue_.pop(); return true; } void shutdown() { std::lock_guard<std::mutex> lock(mutex_); shutdown_ = true; // Wake EVERY waiting consumer so none is left sleeping forever. not_empty_.notify_all(); } private: std::mutex mutex_; std::condition_variable not_empty_; std::queue<T> queue_; bool shutdown_ = false; };Why every line is exception-safe:
- Copying/moving into the
valueparameter ofpushhappens beforemutex_is locked. - Inside
push,std::deque::push_back(used bystd::queue::push) offers the strong exception guarantee: if memory allocation orT's constructor throws,queue_is completely unchanged,lock_guardunlocksmutex_, and no bogusnotify_one()is sent. - Inside
pop,queue_.pop()runs only afterout_valuehas received the value, andunique_lockalways unlocksmutex_.
- Copying/moving into the
Verify with a multi-threaded C++ test program
Compile the test harness below with
g++ -std=c++11 -O2 -pthread(and-fsanitize=threadto check for data races with ThreadSanitizer). In test 3, 4 producers push20,000integers each (0 .. 79,999) while 4 consumers pop concurrently; every item is delivered once, socount == 80,000andsum == 79,999 × 80,000 / 2 = 3,199,960,000(stored in a 64-bitlong longso it does not overflow 32-bitint).#include <atomic> #include <cassert> #include <chrono> #include <cstdio> #include <thread> #include <vector> int main() { // 1. Consumer blocks on empty queue until producer pushes 105. { BlockingQueue<int> tasks; int item = 0; std::thread consumer([&] { bool ok = tasks.pop(item); assert(ok); }); std::this_thread::sleep_for(std::chrono::milliseconds(30)); tasks.push(105); consumer.join(); assert(item == 105); } // 2. shutdown() drains already-pushed items first, then wakes all blocked consumers with false. { BlockingQueue<int> q; q.push(10); q.push(20); std::atomic<int> popped_sum(0); std::atomic<int> false_returns(0); std::vector<std::thread> consumers; for (int i = 0; i < 4; ++i) { consumers.emplace_back([&] { int v = 0; while (q.pop(v)) { popped_sum += v; } ++false_returns; }); } std::this_thread::sleep_for(std::chrono::milliseconds(30)); q.shutdown(); for (auto& t : consumers) { t.join(); } assert(popped_sum == 30); assert(false_returns == 4); } // 3. 4 producers x 20,000 items + 4 consumers: exact delivery of all 80,000 items. { BlockingQueue<int> q; const int num_producers = 4; const int num_consumers = 4; const int items_per_producer = 20000; std::atomic<long long> sum(0); std::atomic<int> count(0); std::vector<std::thread> producers; std::vector<std::thread> consumers; for (int c = 0; c < num_consumers; ++c) { consumers.emplace_back([&] { int v = 0; while (q.pop(v)) { sum += v; ++count; } }); } for (int p = 0; p < num_producers; ++p) { producers.emplace_back([&, p] { for (int i = 0; i < items_per_producer; ++i) { q.push(p * items_per_producer + i); } }); } for (auto& t : producers) { t.join(); } q.shutdown(); for (auto& t : consumers) { t.join(); } long long total = static_cast<long long>(num_producers) * items_per_producer; assert(count == total); assert(sum == total * (total - 1) / 2); } std::puts("All BlockingQueue checks passed!"); return 0; }
Intuition & how it works
Think of BlockingQueue<T> like a restaurant pass-through shelf controlled by a single key (mutex_) and a wakeup bell (not_empty_). Only the thread holding the key may touch the shelf or flip the "Kitchen Closed" sign (shutdown_). When a waiter grabs the key and sees an empty shelf while the kitchen is still open, they hand back the key and nap on a bench until either a chef places a dish on the shelf and taps the bell once (notify_one), or the manager flips the "Kitchen Closed" sign and rings the alarm for every napping waiter (notify_all).
A naive loop like while (queue_.empty()) {} without locking causes a data race (when two threads access the same memory concurrently and at least one writes, causing undefined behavior in C++) while burning 100% of a CPU core spinning usefully on nothing. Conversely, checking if (queue_.empty()) and sleeping without coordinating the check and the sleep under one mutex (a mutual-exclusion lock that lets only one thread inside a critical section at a time) suffers from a lost wake-up (when a producer sends its wakeup signal in the tiny window after a consumer saw an empty queue but before the consumer actually went to sleep, leaving the consumer stuck forever).
Here is a concrete 4-step trace with 1 producer and 2 consumers (C1, C2) sharing an initially empty BlockingQueue<int>:
C1andC2callpop(item): each locksmutex_, seesqueue_.empty() && !shutdown_, and callswait(...)on the condition variable (a synchronization primitive that atomically unlocks a mutex to put a thread to sleep and re-locks the mutex before waking it up).- Producer calls
push(105): locksmutex_, moves105intoqueue_, callsnotify_one(), and unlocksmutex_. C1wakes up, re-locksmutex_, re-checks!queue_.empty() || shutdown_(true), moves105intoitem, popsqueue_, unlocksmutex_, and returnstrue;C2remains asleep using zero CPU.- Coordinator thread calls
shutdown(): locksmutex_, setsshutdown_ = true, and callsnotify_all();C2wakes up, re-locksmutex_, seesqueue_.empty()withshutdown_ == true, unlocksmutex_, and cleanly returnsfalse.
Key points
- Single-mutex invariant eliminates data races. Every read or write of
queue_andshutdown_happens while holdingmutex_, including settingshutdown_ = trueinsideshutdown()so no notification can slip between a consumer's check and itswait(). - Predicate-based
wait(lock, pred)handles races and OS quirks. Wrapping[this] { return !queue_.empty() || shutdown_; }insidewaitre-tests the state in awhileloop after every wake-up, protecting against both another consumer taking the item first and a spurious wake-up (when the OS scheduler wakes a waiting thread even though nobody callednotify_oneornotify_all). notify_one()onpush,notify_all()onshutdown. Pushing 1 element can satisfy at most 1 sleeping consumer, whereas shutting down changes the exit condition for all sleeping consumers simultaneously.- Drain-before-close semantics preserve accepted work.
popchecksif (queue_.empty()) return false;after waking up, so items pushed prior toshutdown()are still consumed in FIFO order beforefalseis returned. - RAII and operation ordering guarantee exception safety. RAII (Resource Acquisition Is Initialization, tying a lock's lifetime to a stack object like
std::lock_guardorstd::unique_lockwhose destructor always unlocks) prevents stuck locks on throw;std::dequeleavesqueue_unchanged ifpushfails to allocate; andpopassignsout_valuebeforequeue_.pop()(re-notifying vianotify_one()if assignment throws) so neither items nor wake-ups are lost. - Time and space complexity.
pushand unblockedpoprun in O(1) amortized time under the mutex (moving oneTinto or out of the underlyingstd::deque),shutdownruns in O(number of waiting threads) to mark them runnable, and memory grows as O(N) forNcurrently queued elements while sleeping threads consume 0% CPU.
Common mistakes
- Using
if (queue_.empty()) cv.wait(lock);instead ofwhile/ predicatewait. If a spurious wake-up occurs—or a second consumer steals the newly pushed item before the woken thread acquiresmutex_—callingqueue_.front()on an emptystd::queuetriggers undefined behavior. - Calling
notify_one()insideshutdown(). Wakes only a single waiting consumer and leaves every other blocked consumer sleeping forever, hangingstd::thread::join(). - Changing
shutdown_tostd::atomic<bool>and skippingmutex_inshutdown(). Atomicity prevents the memory data race on the boolean itself, but STILL suffers the lost wake-up bug ifshutdown_ = true; notify_all();executes after a consumer evaluated the predicate as false and just beforecv.waitputs that consumer to sleep! - Returning
falseimmediately whenshutdown_is true even when!queue_.empty(). Drops already-enqueued items that producers were told succeeded. - Designing
T pop()to return by value instead ofbool pop(T& out_value). First, you have no clean way to signal shutdown without throwing exceptions; second, if copying/moving the return value out ofpop()throws afterqueue_.pop()already removed the element, that element is permanently lost. - Destroying
BlockingQueuewhile threads are still insidepushorpop. Always callshutdown()andjoin()all producer and consumer threads before allowing theBlockingQueueobject to go out of scope.
Follow-up questions
- How would you extend BlockingQueue
with a maximum capacity so fast producers block instead of exhausting memory? Storestd::size_t capacity_(requiringcapacity_ >= 1) alongside a second condition variablenot_full_: inbool push(T value), take astd::unique_lock<std::mutex>and callnot_full_.wait(lock, [this] { return queue_.size() < capacity_ || shutdown_; }), returningfalseifshutdown_became true while waiting. Insidepop, callnot_full_.notify_one()right afterqueue_.pop()frees a slot, and insideshutdown(), callnotify_all()on bothnot_empty_andnot_full_so blocked producers wake up and exit cleanly too. You can also replacestd::queue<T>(backed bystd::deque) with a fixed-size circular buffer (std::vector<T>withhead,tail, andcount) so zero heap allocations ever occur after construction. - Where does a single shared mutex become a bottleneck under high thread counts, and what are the trade-offs of two-lock or lock-free alternatives? Under heavy concurrency, a single mutex forces producers and consumers to take turns even though they touch opposite ends of the queue, causing CPU cache-line ping-ponging and OS context switches. Before jumping to lock-free code, two simpler upgrades usually win: batching (
push_batch/pop_allswapping out the wholestd::queue<T>in O(1) under one lock acquisition) or a two-lock queue (separatehead_mutex_andtail_mutex_with a dummy node so one producer and one consumer run in parallel). A lock-free ring buffer (such as Dmitry Vyukov's bounded MPMC queue) uses compare-and-swap (CAS) (an atomic CPU instruction that updates a variable only if it still equals an expected old value) to eliminate mutex locking, but lock-free linked queues must also solve safe node reclamation and the ABA problem (when a pointer changes fromAtoBand back toA, fooling a CAS check into thinking nothing changed), and still need futex/OS parking when empty so idle consumers do not spin at 100% CPU. - What happens if copying, moving, or assigning an element of type T throws an exception during push or pop, and how do you keep the queue state consistent? Because
void push(T value)acceptsvalueby value, any copy construction from an lvalue caller happens at the call site beforemutex_is even acquired—if it throws, the queue hasn't been touched. Insidepush,queue_.push(std::move(value))invokesT's move constructor (or copy constructor ifThas no move), and the C++ standard guarantees that ifstd::deque::push_backthrows either fromTorstd::bad_alloc, the deque remains completely unmodified (lock_guardunlocksmutex_, andnotify_one()is never reached). Similarly, inpop, ifT's move assignment is notnoexceptand might mutate the source before throwing, you can select copy-assignment viastd::is_nothrow_move_assignable<T>::value(out_value = queue_.front()) beforequeue_.pop()so a throwing assignment leaves the queued element 100% intact and re-notifies another consumer.
Follow-up questions
- How would you extend BlockingQueue<T> with a maximum capacity so fast producers block instead of exhausting memory?
- Where does a single shared mutex become a bottleneck under high thread counts, and what are the trade-offs of two-lock or lock-free alternatives?
- What happens if copying, moving, or assigning an element of type T throws an exception during push or pop, and how do you keep the queue state consistent?
Similar questions
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One
- Increment Digit Array