该文实现了基于C++标准库的线程安全阻塞队列模板类BlockingQueue,支持容量限制、阻塞入队/出队及超时尝试出队;配套生产者生成随机数、消费者取数处理,并通过多线程协同演示完整生产者-消费者模型。

(以下为纯 C++ 多线程阻塞队列 + 生产者消费者模型实现,基于标准库 <queue></queue>、<mutex></mutex>、<condition_variable></condition_variable> 和 <thread></thread>,无第三方依赖,可直接编译运行)
核心思路:用互斥锁保护共享队列,用条件变量让空队列时消费者等待、满队列时生产者等待。C++ 标准库的 std::condition_variable 天然支持“等待某个条件成立”,配合 wait() 和 notify_one()/notify_all() 即可实现线程安全的阻塞行为。
支持任意类型 T,可设容量上限(可选),内部自动处理 wait/notify 逻辑:
#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>
template<typename T>
class BlockingQueue {
private:
std::queue<T> q;
mutable std::mutex mtx;
std::condition_variable not_empty; // 消费者等待:队列非空
std::condition_variable not_full; // 生产者等待:队列未满(若限容)
size_t max_size = 0; // 0 表示无容量限制
public:
explicit BlockingQueue(size_t capacity = 0) : max_size(capacity) {}
// 入队(阻塞直到有空间)
void push(const T& item) {
std::unique_lock<std::mutex> lock(mtx);
if (max_size > 0) {
not_full.wait(lock, [this] { return q.size() < max_size; });
}
q.push(item);
not_empty.notify_one(); // 唤醒一个等待消费的线程
}
// 出队(阻塞直到有数据)
T pop() {
std::unique_lock<std::mutex> lock(mtx);
not_empty.wait(lock, [this] { return !q.empty(); });
T front = std::move(q.front());
q.pop();
if (max_size > 0) {
not_full.notify_one(); // 可能腾出空间,唤醒一个等待生产的线程
}
return front;
}
// 尝试出队(带超时,返回 false 表示超时或为空)
bool try_pop(T& item, int timeout_ms = 0) {
std::unique_lock<std::mutex> lock(mtx);
if (timeout_ms == 0) {
not_empty.wait(lock, [this] { return !q.empty(); });
} else {
auto dur = std::chrono::milliseconds(timeout_ms);
if (!not_empty.wait_for(lock, dur, [this] { return !q.empty(); })) {
return false;
}
}
item = std::move(q.front());
q.pop();
if (max_size > 0) not_full.notify_one();
return true;
}
size_t size() const {
std::lock_guard<std::mutex> lock(mtx);
return q.size();
}
bool empty() const {
std::lock_guard<std::mutex> lock(mtx);
return q.empty();
}
};每个生产者/消费者都是独立函数,通过引用使用同一个队列,适合传给 std::thread:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <thread>
#include <vector>
#include <random>
// 生产者:生成随机数并入队
void producer(BlockingQueue<int>& bq, int id, int count) {
std::mt19937 gen(id);
std::uniform_int_distribution<int> dist(1, 100);
for (int i = 0; i < count; ++i) {
int val = dist(gen);
bq.push(val);
std::cout << "[P" << id << "] pushed " << val << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
// 消费者:取数、打印、简单处理
void consumer(BlockingQueue<int>& bq, int id, int total) {
for (int i = 0; i < total; ++i) {
int val = bq.pop(); // 阻塞等待
std::cout << " [C" << id << "] popped " << val << "\n";
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}注意:需确保生产总数 ≥ 消费总数,否则消费者会永久阻塞(实际项目中建议加退出信号或使用 `try_pop` + 超时 + 中断机制):
int main() {
BlockingQueue<int> bq(10); // 容量为 10 的有界队列
const int num_producers = 2;
const int num_consumers = 3;
const int items_per_producer = 5;
std::vector<std::thread> threads;
// 启动生产者
for (int i = 0; i < num_producers; ++i) {
threads.emplace_back(producer, std::ref(bq), i, items_per_producer);
}
// 启动消费者(总消费数 = 总生产数)
int total_items = num_producers * items_per_producer;
for (int i = 0; i < num_consumers; ++i) {
int each = total_items / num_consumers;
int rest = (i == 0) ? total_items % num_consumers : 0;
threads.emplace_back(consumer, std::ref(bq), i, each + rest);
}
// 等待所有线程结束
for (auto& t : threads) {
if (t.joinable()) t.join();
}
std::cout << "All done.\n";
return 0;
}std::unique_lock 配合 wait:它允许在等待期间临时释放锁,并在唤醒后自动重新加锁;普通 lock_guard 不支持wait(lock) 后手动判断notify_one() 更高效std::move(q.front()) 避免不必要的拷贝(尤其对大对象)unique_lock / lock_guard)保证异常时自动解锁基本上就这些。不复杂但容易忽略条件变量的谓词写法和锁的搭配——写对了,就是教科书级的线程安全阻塞队列。
以上就是c++++怎么实现一个阻塞队列_c++生产者消费者模型实现【多线程】的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号