Implementing bounded blocking queue in C++
Here's a C++ example of a bounded blocking queue using std::mutex and std::condition_variable with while loops to handle spurious wakeups, plus a simple producer-consumer demo using threads.
Below is a C++ example of a bounded blocking queue implemented strictly with std::mutex and std::condition_variable. Both push (for producers) and pop (for consumers) wait using a while loop to handle spurious wake-ups. A simple main function shows how multiple producers and consumers might use this queue.
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <chrono>
// A thread-safe bounded buffer for generic types.
template <typename T>
class BoundedBuffer {
public:
explicit BoundedBuffer(std::size_t capacity) : capacity_(capacity) {}
// Enqueue an element, blocking if the buffer is full.
void push(const T& item) {
std::unique_lock<std::mutex> lock(mutex_);
// Wait until not full
not_full_.wait(lock, [this]() { return buffer_.size() < capacity_; });
buffer_.push(item);
// Notify one waiting consumer
not_empty_.notify_one();
}
// Dequeue an element, blocking if the buffer is empty.
T pop() {
std::unique_lock<std::mutex> lock(mutex_);
// Wait until not empty
not_empty_.wait(lock, [this]() { return !buffer_.empty(); });
T item = buffer_.front();
buffer_.pop();
// Notify one waiting producer
not_full_.notify_one();
return item;
}
private:
std::size_t capacity_;
std::queue<T> buffer_;
std::mutex mutex_;
std::condition_variable not_empty_;
std::condition_variable not_full_;
};
int main() {
const std::size_t buffer_capacity = 10;
BoundedBuffer<int> buffer(buffer_capacity);
const int NUM_PRODUCERS = 3;
const int NUM_CONSUMERS = 2;
const int ITEMS_PER_PRODUCER = 20;
// Producer threads
std::vector<std::thread> producers;
for (int i = 0; i < NUM_PRODUCERS; ++i) {
producers.emplace_back([i, &buffer]() {
for (int j = 0; j < ITEMS_PER_PRODUCER; ++j) {
int value = i * 100 + j; // just an example value
buffer.push(value);
std::cout << "Producer " << i << " pushed " << value << "\n";
// Sleep for a short while to simulate work
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
});
}
// Consumer threads
std::vector<std::thread> consumers;
for (int i = 0; i < NUM_CONSUMERS; ++i) {
consumers.emplace_back([i, &buffer, total = NUM_PRODUCERS * ITEMS_PER_PRODUCER]() {
// Each consumer will attempt to pop a share of items
for (int count = 0; count < total / NUM_CONSUMERS + 5; ++count) {
int item = buffer.pop();
std::cout << "Consumer " << i << " popped " << item << "\n";
// Sleep for a short while to simulate work
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
});
}
// Join all threads
for (auto &prod : producers) {
prod.join();
}
for (auto &cons : consumers) {
cons.join();
}
std::cout << "All producers and consumers finished.\n";
return 0;
}
Key Points
- Bounded Buffer: The queue has a fixed
capacity_, so producers block if the buffer is full, and consumers block if it’s empty.
- Mutex: All modifications to the underlying queue are protected by a single
std::mutex.
- Condition Variables:
not_full_ is used to signal when producers can add more items; not_empty_ signals when consumers can remove items.
- Spurious Wakeups: The calls to
wait are placed inside lambdas used by wait, which internally loops (or you can explicitly use a while loop). This ensures a thread will re-check the condition upon any wakeup.
You can adjust the number of producers/consumers and items to see how the queue behaves under load.