C++ condition_variable教程_C++生产者消费者模型实现详解
发布时间:2025-11-29 15:51
发布者:网络
浏览次数:condition_variable用于C++多线程同步,配合mutex实现生产者-消费者模型:生产者在缓冲区满时等待,消费者在空时等待,通过wait+谓词避免虚假唤醒,notify_all通知对应线程,确保安全高效协作。

在C++多线程编程中,condition_variable 是实现线程间同步的重要工具之一。它常用于解决生产者-消费者这类协作问题,确保多个线程在共享资源访问时能够安全、高效地协同工作。
condition_variable 基本概念
condition_variable 定义在
关键成员函数包括:
- wait(lock, predicate):释放锁并阻塞线程,直到被唤醒且谓词为真
- notify_one():唤醒一个等待的线程
- notify_all():唤醒所有等待的线程
使用 wait 时推荐传入谓词(lambda 或函数对象),避免虚假唤醒带来的问题。
生产者-消费者模型设计思路
该模型包含两类线程:
- 生产者:向共享缓冲区添加数据
- 消费者:从缓冲区取出数据处理
需要解决的问题:
- 缓冲区满时,生产者应等待
- 缓冲区空时,消费者应等待
- 对缓冲区的访问必须互斥
为此引入:
N世界
一分钟搭建会展元宇宙
138
查看详情
- 一个互斥量(mutex)保护缓冲区
- 一个 condition_variable 供生产者等待
- 另一个 condition_variable 供消费者等待
代码实现示例
以下是一个完整的 C++ 实现:
#include <iostream> #include <thread> #include <queue> #include <mutex> #include <condition_variable> #include <chrono> std::queue<int> buffer; std::mutex mtx; std::condition_variable cv_full; // 缓冲区未满 std::condition_variable cv_empty; // 缓冲区非空 const int max_size = 5; void producer(int id) { for (int i = 0; i < 10; ++i) { std::unique_lock<std::mutex> lock(mtx); cv_full.wait(lock, []{ return buffer.size() < max_size; }); buffer.push(i); std::cout << "生产者 " << id << " 生产: " << i << "\n"; lock.unlock(); cv_empty.notify_all(); // 通知消费者可以消费 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); cv_empty.wait(lock, []{ return !buffer.empty(); }); int value = buffer.front(); buffer.pop(); std::cout << "消费者 " << id << " 消费: " << value << "\n"; lock.unlock(); cv_full.notify_all(); // 通知生产者可以生产 std::this_thread::sleep_for(std::chrono::milliseconds(150)); } }
main 函数启动多个生产者和消费者:
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;
}
注意事项与最佳实践
使用 condition_variable 时需注意:
- 始终使用 unique_lock
而不是 lock_guard,因为 wait 会原子性地释放锁 - wait 的谓词判断必不可少,防止虚假唤醒导致逻辑错误
- notify 后不必立即释放锁,但应尽快减少临界区范围
- 考虑使用 notify_one() 减少不必要的线程唤醒开销,除非确实需要唤醒全部等待者
在实际项目中,可将缓冲区封装成一个线程安全的类,隐藏同步细节,提高代码复用性。
基本上就这些。掌握 condition_variable 的正确用法,是写出健壮多线程程序的关键一步。
以上就是C++ condition_variable教程_C++生产者消费者模型实现详解的详细内容,更多请关注其它相关文章!
# 工具
# ai
# c++
# ios
# stream
# 代码复用
# red
# 多线程
# 如何实现
# 多个
# 复用
# 如何使用
# 有什么区别
# 是一个
# 编解码
# 互斥
# 相关文章
# 利通区大数据全网营销推广怎么做
# 营销策划与推广照片
# 太原网站建设市场分析
# 长沙网站建设课程总结
# 苹果生鲜营销推广文案范文
# 兄弟素材网站建设需要
# 东莞优化网站单价
# Wp中文seo插件
# 泉州seo优化指南
# 都江堰网站推广选哪家





clude <mutex>
#include <condition_variable>
#include <chrono>
std::queue<int> buffer;
std::mutex mtx;
std::condition_variable cv_full; // 缓冲区未满
std::condition_variable cv_empty; // 缓冲区非空
const int max_size = 5;
void producer(int id) {
for (int i = 0; i < 10; ++i) {
std::unique_lock<std::mutex> lock(mtx);
cv_full.wait(lock, []{ return buffer.size() < max_size; });
buffer.push(i);
std::cout << "生产者 " << id << " 生产: " << i << "\n";
lock.unlock();
cv_empty.notify_all(); // 通知消费者可以消费
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);
cv_empty.wait(lock, []{ return !buffer.empty(); });
int value = buffer.front();
buffer.pop();
std::cout << "消费者 " << id << " 消费: " << value << "\n";
lock.unlock();
cv_full.notify_all(); // 通知生产者可以生产
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
}