生产者消费者模型通过互斥锁和条件变量实现线程安全的缓冲区共享,生产者在缓冲区未满时添加数据,消费者在非空时取出数据,配合谓词等待避免虚假唤醒,使用notify_one提升效率,可通过结束标志正常退出线程。

生产者消费者模型是多线程编程中的经典问题,用于描述多个线程之间如何安全地共享有限缓冲区的数据。C++中可以通过标准库的多线程支持(<thread></thread>、<mutex></mutex>、<condition_variable></condition_variable>)高效实现该模型。
核心组件包括一个共享缓冲区、互斥锁保护数据访问、两个条件变量分别通知“有空位”和“有数据”。生产者在缓冲区未满时添加数据,消费者在缓冲区非空时取出数据。
以下是一个基于固定大小队列的实现示例:
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>
std::queue<int> buffer;
std::mutex mtx;
std::condition_variable not_full;
std::condition_variable not_empty;
const int max_size = 5;
void producer(int id) {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(mtx);
not_full.wait(lock, []() { return buffer.size() < max_size; });
buffer.push(i);
std::cout << "Producer " << id << " produced: " << i << "\n";
lock.unlock();
not_empty.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void consumer(int id) {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(mtx);
not_empty.wait(lock, []() { return !buffer.empty(); });
int value = buffer.front();
buffer.pop();
std::cout << "Consumer " << id << " consumed: " << value << "\n";
lock.unlock();
not_full.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}
在主函数中启动多个生产者和消费者线程即可观察协同工作:
立即学习“C++免费学习笔记(深入)”;
int main() {
std::thread p1(producer, 1);
std::thread p2(producer, 2);
std::thread c1(consumer, 1);
std::thread c2(consumer, 2);
p1.join();
p2.join();
c1.join();
c2.join();
return 0;
}
条件变量等待必须配合谓词使用:避免虚假唤醒导致逻辑错误。例如 not_full.wait(lock, [](){ return buffer.size() 确保只有真正满足条件时才继续执行。
notify_one 与 notify_all 的选择:若只有一个等待线程需被唤醒,用 notify_one 更高效;若存在多个同类等待者,根据场景决定是否广播。
解锁后通知:先释放锁再调用 notify 可减少唤醒后立即阻塞的概率,提升性能。
std::atomic 标记运行状态,避免强制终止线程加入结束控制的简单方式是在共享区域添加:
bool done = false;
// 消费者中检测
not_empty.wait(lock, []() { return !buffer.empty() || done; });
if (done && buffer.empty()) break;
以上就是C++怎么实现生产者消费者模型_C++多线程并发模型与生产者消费者实现的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号