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) — Appends value to 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 into out_value and returns true. When the queue is empty and still open, the caller sleeps without busy-waiting until an element arrives or the queue closes. Returns false once 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 before pop returns false to every waiting consumer.
  • Exception safety & type-system hygiene: Disable nonsensical copy operations on the queue itself and preserve invariants if copying, moving, or assigning T throws an exception.

Step-by-step walkthrough

  1. 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 into out_value and returns true. If the queue is currently empty and still open, the calling thread sleeps until an item arrives or the queue shuts down. Returns false only 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 5 pop calls still return those 5 items (true), and only once the queue is empty does pop return false. That way accepted work is never silently lost.
    • push after shutdown throws std::logic_error: since push returns void, throwing is the cleanest way to surface a caller bug instead of silently dropping data.
    • Copying the queue is disabled (= delete): std::mutex and std::condition_variable cannot be copied, and copying a live thread channel has no sensible meaning.
  2. 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) ---> Consumers
    
    • std::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) when queue_ is empty.
    • std::queue<T> queue_: the underlying first-in, first-out container (std::deque<T> by default).
    • bool shutdown_ = false: set to true once shutdown() is called.

    One golden invariant prevents every data race and lost signal: every read and every write of queue_ or shutdown_ happens while holding mutex_. A condition variable never protects data on its own—it simply lets a thread atomically release mutex_ to fall asleep and re-acquire mutex_ 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;
    };
    
  3. Implement push with RAII locking and notify_one

    In push(T value), we acquire mutex_ using std::lock_guard<std::mutex>. This is RAII (Resource Acquisition Is Initialization): the constructor locks mutex_, and the destructor is guaranteed to unlock mutex_ when lock leaves scope—even if an exception is thrown.

    Taking value by value lets callers pass either an lvalue (copied at the call site before locking) or an rvalue/move-only type like std::unique_ptr<int> (moved in with zero copies), and we std::move(value) into queue_. Finally, we call not_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 lock across notify_one() keeps the code compact and avoids a subtle lifetime hazard where another thread pops the final item and destroys the BlockingQueue before notify_one() finishes executing.

  4. Implement pop using a predicate wait loop

    In pop(T& out_value), we use std::unique_lock<std::mutex> instead of std::lock_guard because not_empty_.wait(...) needs to unlock mutex_ while sleeping and re-lock it upon waking.

    Never write if (queue_.empty()) not_empty_.wait(lock);! Always pass a predicate lambda so wait runs a while loop 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 called notify).

    Once wait returns with mutex_ locked, !queue_.empty() || shutdown_ is guaranteed true:

    • If queue_ is NOT empty, we move the front element into out_value before calling queue_.pop(), and return true. If T's assignment throws an exception, the item has not been popped yet, and we call not_empty_.notify_one() in catch (...) so another waiting consumer still gets woken for that item!
    • If queue_ IS empty, shutdown_ must be true, so we return false.
        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;
        }
    
  5. Implement shutdown without losing wake-ups

    shutdown() sets shutdown_ = true under mutex_ and calls not_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:

    1. Calling notify_one() instead of notify_all(): if 4 consumers are sleeping on an empty queue, notify_one() wakes only 1 consumer (which returns false and exits), leaving the other 3 threads sleeping forever so thread.join() deadlocks!
    2. Updating shutdown_ without locking mutex_ (even if shutdown_ is std::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 FOREVER
    

    Because Consumer holds mutex_ continuously from checking the predicate until wait() atomically puts it on the sleep queue, locking mutex_ inside shutdown() makes it impossible for notify_all() to slip into that gap.

  6. 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 value parameter of push happens before mutex_ is locked.
    • Inside push, std::deque::push_back (used by std::queue::push) offers the strong exception guarantee: if memory allocation or T's constructor throws, queue_ is completely unchanged, lock_guard unlocks mutex_, and no bogus notify_one() is sent.
    • Inside pop, queue_.pop() runs only after out_value has received the value, and unique_lock always unlocks mutex_.
  7. Verify with a multi-threaded C++ test program

    Compile the test harness below with g++ -std=c++11 -O2 -pthread (and -fsanitize=thread to check for data races with ThreadSanitizer). In test 3, 4 producers push 20,000 integers each (0 .. 79,999) while 4 consumers pop concurrently; every item is delivered once, so count == 80,000 and sum == 79,999 × 80,000 / 2 = 3,199,960,000 (stored in a 64-bit long long so it does not overflow 32-bit int).

    #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>:

  1. C1 and C2 call pop(item): each locks mutex_, sees queue_.empty() && !shutdown_, and calls wait(...) 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).
  2. Producer calls push(105): locks mutex_, moves 105 into queue_, calls notify_one(), and unlocks mutex_.
  3. C1 wakes up, re-locks mutex_, re-checks !queue_.empty() || shutdown_ (true), moves 105 into item, pops queue_, unlocks mutex_, and returns true; C2 remains asleep using zero CPU.
  4. Coordinator thread calls shutdown(): locks mutex_, sets shutdown_ = true, and calls notify_all(); C2 wakes up, re-locks mutex_, sees queue_.empty() with shutdown_ == true, unlocks mutex_, and cleanly returns false.

Key points

  • Single-mutex invariant eliminates data races. Every read or write of queue_ and shutdown_ happens while holding mutex_, including setting shutdown_ = true inside shutdown() so no notification can slip between a consumer's check and its wait().
  • Predicate-based wait(lock, pred) handles races and OS quirks. Wrapping [this] { return !queue_.empty() || shutdown_; } inside wait re-tests the state in a while loop 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 called notify_one or notify_all).
  • notify_one() on push, notify_all() on shutdown. 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. pop checks if (queue_.empty()) return false; after waking up, so items pushed prior to shutdown() are still consumed in FIFO order before false is 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_guard or std::unique_lock whose destructor always unlocks) prevents stuck locks on throw; std::deque leaves queue_ unchanged if push fails to allocate; and pop assigns out_value before queue_.pop() (re-notifying via notify_one() if assignment throws) so neither items nor wake-ups are lost.
  • Time and space complexity. push and unblocked pop run in O(1) amortized time under the mutex (moving one T into or out of the underlying std::deque), shutdown runs in O(number of waiting threads) to mark them runnable, and memory grows as O(N) for N currently queued elements while sleeping threads consume 0% CPU.

Common mistakes

  • Using if (queue_.empty()) cv.wait(lock); instead of while / predicate wait. If a spurious wake-up occurs—or a second consumer steals the newly pushed item before the woken thread acquires mutex_—calling queue_.front() on an empty std::queue triggers undefined behavior.
  • Calling notify_one() inside shutdown(). Wakes only a single waiting consumer and leaves every other blocked consumer sleeping forever, hanging std::thread::join().
  • Changing shutdown_ to std::atomic<bool> and skipping mutex_ in shutdown(). Atomicity prevents the memory data race on the boolean itself, but STILL suffers the lost wake-up bug if shutdown_ = true; notify_all(); executes after a consumer evaluated the predicate as false and just before cv.wait puts that consumer to sleep!
  • Returning false immediately when shutdown_ is true even when !queue_.empty(). Drops already-enqueued items that producers were told succeeded.
  • Designing T pop() to return by value instead of bool pop(T& out_value). First, you have no clean way to signal shutdown without throwing exceptions; second, if copying/moving the return value out of pop() throws after queue_.pop() already removed the element, that element is permanently lost.
  • Destroying BlockingQueue while threads are still inside push or pop. Always call shutdown() and join() all producer and consumer threads before allowing the BlockingQueue object 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? Store std::size_t capacity_ (requiring capacity_ >= 1) alongside a second condition variable not_full_: in bool push(T value), take a std::unique_lock<std::mutex> and call not_full_.wait(lock, [this] { return queue_.size() < capacity_ || shutdown_; }), returning false if shutdown_ became true while waiting. Inside pop, call not_full_.notify_one() right after queue_.pop() frees a slot, and inside shutdown(), call notify_all() on both not_empty_ and not_full_ so blocked producers wake up and exit cleanly too. You can also replace std::queue<T> (backed by std::deque) with a fixed-size circular buffer (std::vector<T> with head, tail, and count) 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_all swapping out the whole std::queue<T> in O(1) under one lock acquisition) or a two-lock queue (separate head_mutex_ and tail_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 from A to B and back to A, 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) accepts value by value, any copy construction from an lvalue caller happens at the call site before mutex_ is even acquired—if it throws, the queue hasn't been touched. Inside push, queue_.push(std::move(value)) invokes T's move constructor (or copy constructor if T has no move), and the C++ standard guarantees that if std::deque::push_back throws either from T or std::bad_alloc, the deque remains completely unmodified (lock_guard unlocks mutex_, and notify_one() is never reached). Similarly, in pop, if T's move assignment is not noexcept and might mutate the source before throwing, you can select copy-assignment via std::is_nothrow_move_assignable<T>::value (out_value = queue_.front()) before queue_.pop() so a throwing assignment leaves the queued element 100% intact and re-notifies another consumer.

Follow-up questions

Similar questions

More Belvederetrading interview questions

All 1 Belvederetrading questions →