
阻塞队列是一种线程安全的队列,当队列为空时,消费者线程调用 pop() 会自动等待,直到有新元素入队;当队列为满时(如有容量限制),生产者线程调用 push() 也会等待,直到有空位。这种“自动等待+唤醒”机制,天然适配生产者-消费者模型。
要用 C++ 实现一个可靠的阻塞队列,需结合以下三要素:
下面是一个简洁、可直接运行的无界阻塞队列实现(支持 move 语义,线程安全):
#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>
<p>template <typename T>
class BlockingQueue {
private:
std::queue<T> queue<em>;
mutable std::mutex mtx</em>;
std::condition_variable not<em>empty</em>;
std::condition_variable not<em>full</em>; // 可选,无界时仅作占位</p><p>public:
void push(T item) {
std::unique<em>lock<std::mutex> lock(mtx</em>);
queue_.push(std::move(item));
not<em>empty</em>.notify_one(); // 唤醒等待消费的线程
}</p><pre class='brush:php;toolbar:false;'>T pop() {
std::unique_lock<std::mutex> lock(mtx_);
not_empty_.wait(lock, [this] { return !queue_.empty(); });
T item = std::move(queue_.front());
queue_.pop();
return item;
}
// 带超时的 pop(避免永久阻塞)
bool pop(T& item, std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lock(mtx_);
if (not_empty_.wait_for(lock, timeout, [this] { return !queue_.empty(); })) {
item = std::move(queue_.front());
queue_.pop();
return true;
}
return false;
}
bool empty() const {
std::unique_lock<std::mutex> lock(mtx_);
return queue_.empty();
}};
立即学习“C++免费学习笔记(深入)”;
用上面的 BlockingQueue
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
<p>BlockingQueue<int> bq;</p><p>void producer(int id, int count) {
for (int i = 0; i < count; ++i) {
int val = id * 100 + i;
bq.push(val);
std::cout << "[P" << id << "] pushed " << val << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}</p><p>void consumer(int id) {
while (true) {
int val;
if (bq.pop(val, std::chrono::milliseconds(500))) {
std::cout << "[C" << id << "] consumed " << val << "\n";
} else {
std::cout << "[C" << id << "] timeout, exiting...\n";
break;
}
}
}</p><p>int main() {
std::vector<std::thread> producers, consumers;</p><pre class='brush:php;toolbar:false;'>// 启动 2 个生产者,各发 3 个数
for (int i = 0; i < 2; ++i) {
producers.emplace_back(producer, i, 3);
}
// 启动 3 个消费者
for (int i = 0; i < 3; ++i) {
consumers.emplace_back(consumer, i);
}
for (auto& t : producers) t.join();
for (auto& t : consumers) t.join();
return 0;}
编译运行时加 -std=c++17 -pthread。输出会交错显示生产和消费过程,体现线程间自然同步。
实际工程中还需考虑:
以上就是c++++如何实现一个阻塞队列 c++生产者消费者模型【实例】的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号