C++11/std::condition_variable – 生产者消费者模型
代码示例:
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <deque>
#include <condition_variable>
std::deque<int> global_deque;
std::mutex global_mutex;
std::condition_variable global_ConditionVar;
// 生产者线程
void Producer()
{
while (true)
{
// 休眠5毫秒
std::this_thread::sleep_for(std::chrono::milliseconds(5));
std::unique_lock<std::mutex> lock(global_mutex);
global_deque.push_front(1);
std::cout << "生产者生产了数据" << std::endl;
global_ConditionVar.notify_all();
}
}
// 消费者线程
void Consumer()
{
while (true)
{
std::unique_lock<std::mutex> lock(global_mutex);
// 当队列为空时返回false,则一直阻塞在这一行
global_ConditionVar.wait(lock, [] {return !global_deque.empty(); });
global_deque.pop_back();
std::cout << "消费者消费了数据" << std::endl;
global_ConditionVar.notify_all();
}
}
int main()
{
std::thread consumer_Thread(Consumer);
//std::thread consumer_Thread1(Consumer);
std::thread producer_Thread(Producer);
consumer_Thread.join();
//consumer_Thread1.join();
producer_Thread.join();
getchar();
return 0;
}
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++11/std::condition_variable – 生产者消费者模型
原文链接:https://www.stubbornhuang.com/779/
发布于:2020年04月01日 17:44:25
修改于:2020年04月01日 17:46:06
当前分类随机文章推荐
- C++11/std::atomic - 原子变量(不加锁实现线程互斥) 阅读6902次,点赞2次
- C++ - GBK编码下的全角字符转半角字符 阅读2079次,点赞0次
- C++STL容器 - std::map查找元素与判断键值是否存在方法总结 count,find,contains,equal_range,lower_bound,upper_bound 阅读1264次,点赞0次
- C++ - std::string替换字符串中所有指定的子字符串 阅读4145次,点赞1次
- C++ - 阿拉伯数字字符串转换为中文读法的中文字符串,支持小数点 阅读1616次,点赞0次
- C++ - Windows系统获取桌面路径 阅读462次,点赞0次
- C++ - Yolo的letterbox图片预处理方法,缩放图片不失真 阅读308次,点赞0次
- C++ - 对字符串和图片进行base64编解码 阅读1083次,点赞0次
- C++ - queue存储动态指针时正确释放内存 阅读6201次,点赞2次
- C++ - 数组初始化 阅读568次,点赞0次
全站随机文章推荐
- 资源分享 - Real-Time Volume Graphics 英文高清PDF下载 阅读2298次,点赞0次
- 资源分享 - 3D Math Primer for Graphics and Game Development (Second Edition) 英文高清PDF下载 阅读2920次,点赞1次
- Python - 爬取直播吧首页重要赛事赛程信息 阅读640次,点赞0次
- Pytorch - masked_fill方法参数详解与使用 阅读1312次,点赞0次
- 资源分享 - 神经网络与深度学习应用实战(刘凡平著)PDF下载 阅读2579次,点赞0次
- 资源分享 - GPGPU Programming for Games and Science 英文高清PDF下载 阅读1827次,点赞0次
- GCC/G++中编译优化选项-O -O0 -O1 -O2 -O3 -Os -Ofast -Og -Oz各自的区别和作用 阅读5762次,点赞4次
- 网站推荐 - 注册chatGPT无法接收验证短信?使用便宜好用的sms-activate 阅读4850次,点赞2次
- Python - 安装onnxruntime-gpu出现ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: '...\\numpy-1.23.1.dist-info\\METADATA' 阅读1007次,点赞0次
- C++ - const修饰符与指针 阅读599次,点赞1次
评论
169