C++11/std::condition_variable – 生产者消费者模型
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:C++11/std::condition_variable – 生产者消费者模型
原文链接:https://www.stubbornhuang.com/779/
发布于:2020年04月01日 17:44:25
修改于:2020年04月01日 17:46:06
代码示例:
#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;
}
当前分类随机文章推荐
- C++ - std::numeric_limits
简介与使用,用于获取指定数据类型的最大值与最小值 阅读397次,点赞0次 - C++ - single header跨平台高效开源日志库Easylogging++的配置和使用 阅读577次,点赞0次
- C++ - std::string输出双引号到字符串 阅读3238次,点赞0次
- C++ - 我的代码风格/代码规范备忘 阅读909次,点赞0次
- C++STL容器 - std::map容器修改、元素操作总结 clear,insert,emplace,erase,swap,merge,extract,insert_or_assign等 阅读1633次,点赞0次
- C++11 - 使用std::chrono计算程序、函数运行时间 阅读2780次,点赞0次
- C++ - windows、linux跨平台递归创建多级目录 阅读199次,点赞0次
- C++ - 使用Websocket++编写客户端连接WebSocket服务器并进行通信 阅读4382次,点赞3次
- C++11/std::thread - 线程管理join/detach 阅读2402次,点赞0次
- C++ - 对字符串和图片进行base64编解码 阅读328次,点赞0次
全站随机文章推荐
- 资源分享 - GPU Pro 1 - Advanced Rendering Techniques 英文高清PDF下载 阅读3076次,点赞0次
- 资源分享 - 交互式计算机图形学:基于OpenGL着色器的自顶向下方法(第六版),Interactive Computer Graphics - A top-down approach with shader-based OpenGL(Six 6th Edition)中文版PDF下载 阅读865次,点赞0次
- 工具网站推荐 - DLL‑FILES.COM帮你找到你的应用程序所缺失的dll文件 阅读2575次,点赞0次
- Python3爬虫 - requests的请求响应状态码(requests.status_code) 阅读9259次,点赞4次
- 资源分享 - Game Programming Gems 4 英文高清PDF下载 阅读2322次,点赞1次
- 书籍翻译 - Fundamentals of Computer Graphics, Fourth Edition 虎书第四版中文翻译 阅读4751次,点赞14次
- Duilib - 点击程序关闭按钮最小化到托盘,点击托盘按钮恢复 阅读1741次,点赞0次
- 资源分享 - AI Game Programming Wisdom 4 英文高清PDF下载 阅读1406次,点赞0次
- 计算几何与计算机图形学必读书单整理 阅读19628次,点赞19次
- C++ – 字节数组byte[]或者unsigned char[]与float的相互转换 阅读2025次,点赞0次
评论
169