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++ - Windows获取电脑上摄像头设备数目、名字以及id 阅读97次,点赞0次
- C++ - 在某一天某个时间点定时执行任务,比如2022年9月19日晚上9点准点执行发送邮件函数 阅读232次,点赞0次
- C++STL容器 - std::map容器修改、元素操作总结 clear,insert,emplace,erase,swap,merge,extract,insert_or_assign等 阅读1091次,点赞0次
- C++ - 字节数组byte[]或者unsigned char[]与long的相互转换 阅读736次,点赞0次
- C++ - 拷贝构造函数与拷贝构造函数调用时机 阅读152次,点赞0次
- C++ - Windows下字符串UTF8编码转ANSI,ANSI转UTF8编码 阅读241次,点赞0次
- C++ – 字节数组byte[]或者unsigned char[]与short的相互转换 阅读979次,点赞0次
- C++ - return this和return *this的含义和区别 阅读163次,点赞0次
- C++ 回调函数 阅读2784次,点赞0次
- C++11 - 委托机制的实现TinyDelegate 阅读1200次,点赞0次
全站随机文章推荐
- 资源分享 - ShaderX3 - Advanced Rendering with DirectX and OpenGL 英文高清PDF下载 阅读1984次,点赞0次
- TensorRT - workspace的作用 阅读155次,点赞0次
- 资源分享 - 白话大数据与机器学习(高扬著)PDF下载 阅读2337次,点赞0次
- Duilib - 颜色属性的设置 阅读3039次,点赞1次
- Python - 深度学习训练过程使用matplotlib.pyplot实时动态显示loss和acc曲线 阅读2029次,点赞0次
- Unity - Color32[]转IntPtr 阅读2739次,点赞1次
- 深度学习 - 图解Transformer,小白也能看懂的Transformer处理过程 阅读575次,点赞0次
- 客户端开发GUI框架对比与技术选型总结 阅读2839次,点赞0次
- 书籍翻译 - Cloth Simulation for Computer Graphics 中文翻译 阅读354次,点赞0次
- 神经网络 - 模型训练需注意的细节与超参数调优 阅读557次,点赞1次
评论
164