ConcurrencyC++verifiedVerified

Producer-Consumer Pattern in C++

Decouple data production from data consumption using a shared buffer, allowing each side to operate at its own pace.

How to Implement the Producer-Consumer Pattern in C++

1Step 1: Define a thread-safe bounded queue

template <typename T>
class BlockingQueue {
    std::queue<T> queue_;
    std::mutex mu_;
    std::condition_variable notEmpty_;
    std::condition_variable notFull_;
    size_t maxSize_;

public:
    explicit BlockingQueue(size_t maxSize) : maxSize_(maxSize) {}

2Step 2: Producer pushes items (blocks when full)

    void push(T item) {
        std::unique_lock lock(mu_);
        notFull_.wait(lock, [this] { return queue_.size() < maxSize_; });
        queue_.push(std::move(item));
        notEmpty_.notify_one();
    }

3Step 3: Consumer pops items (blocks when empty)

    T pop() {
        std::unique_lock lock(mu_);
        notEmpty_.wait(lock, [this] { return !queue_.empty(); });
        T item = std::move(queue_.front());
        queue_.pop();
        notFull_.notify_one();
        return item;
    }
};

int main() {
    BlockingQueue<std::string> queue(5);

    // Producer thread
    std::thread producer([&queue] {
        for (int i = 0; i < 10; ++i) {
            queue.push("item-" + std::to_string(i));
            std::cout << "Produced: item-" << i << "\n";
        }
    });

    // Consumer thread
    std::thread consumer([&queue] {
        for (int i = 0; i < 10; ++i) {
            auto item = queue.pop();
            std::cout << "Consumed: " << item << "\n";
        }
    });

    producer.join();
    consumer.join();
}

Producer-Consumer Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Producer-Consumer Pattern in the Real World

Think of a bakery where bakers (producers) place fresh loaves on a display shelf (the queue) and customers (consumers) pick them up at their leisure. The shelf decouples the baking schedule from customer arrival times — bakers keep baking even when no customer is present, and customers keep shopping even when bakers are on break.