当前位置:网站首页>生产者-消费者线程模型学习
生产者-消费者线程模型学习
2022-08-09 15:45:00 【老乐大魔王】
生产者消费者模型基本框架:
也就是一个线程扮演生产者往资源池放入数据,另一个线程扮演消费者从资源池中取出数据(当资源池为空时不能取数据),因为资源池是共享的,所以需要互斥量保证当一个线程操作资源池时,另一个线程不能操作资源池,也就是生产和和消费者不能同时操作资源池
涉及技术
unique_lock
+mutex
+condition_variable
代码实现:
#include<iostream>
#include<thread>
#include<mutex>
#include<deque>
#include<condition_variable>
using std::cout;
using std::endl;
std::mutex m;
std::deque<int> q;
std::condition_variable con;
void producer() {
int count = 10;
while (count > 0) {
std::unique_lock<std::mutex> locker(m);
q.push_front(count);
cout << "producer producer a value "<<count<<" !" << endl;
locker.unlock();
//1.unique_lock有unlock功能,lock_guard妹有
//2.由于notify_one不需要被互斥保护,所以可以提前unlock(尽量使用细粒度锁)
con.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
--count;
}
}
void consumer() {
int data = 0;
while (data != 1) {
std::unique_lock<std::mutex> locker(m);
con.wait(locker, []() {
return !q.empty();});
//1.休眠直到deque内有东西才会被producer唤醒
//2.locker睡眠的时候会调用unlock(),直到被唤醒又会继续持有锁保证后面的操作是安全的
//3.传入lambda函数是为了防止系统造成的伪唤醒,这是我们不想看到的
data = q.back();
q.pop_back();
locker.unlock();
cout << "cosumer got value "<<data<< " from producer!" << endl;
}
}
int main() {
std::thread thread1(producer);
std::thread thread2(consumer);
thread1.join();
thread2.join();
return 0;
}
边栏推荐
- MySQL 5.5 series installation steps tutorial (graphical version)
- 机器学习强基计划1-2:图文详解线性回归与局部加权线性回归+房价预测实例
- 计组——大端方式和小端方式相关题目
- 良匠-手把手教你写NFT抢购软(二)
- B44 - Based on stm32 bluetooth intelligent voice recognition classification broadcast trash
- 2.1, pay attention to the network based on parallel context scenario text image super-resolution
- C语言小游戏—扫雷
- A51 - 基于STM32的DHT11和LCD显示串口通信仿真
- 网络——IPv6 vs IPv4
- 2.1、基于并行上下文注意网络的场景文本图像超分辨率
猜你喜欢
随机推荐
CocosCreator accesses WeChat mini-games
利用C#传输Json数据
A42 - 基于51单片机的洗衣机设计
1.1、VIFB: A Visible and Infrared Image Fusion Benchmark(一个可见光与红外图像融合Benchmark)文章阅读
现在,怎么挑选舞台租赁LED显示屏?
SQL trill interview: send you a universal template, to?(key, each user to log on to the maximum number of consecutive monthly)
BETA:一个用于计算药物靶标预测的综合基准
[1413. Stepwise summation to get the minimum value of positive numbers]
PADS生成位号图
OpenCV 图像变换之 —— 拉伸、收缩、扭曲和旋转
CocosCreator接入微信小游戏
MySQL 5.5系列安装步骤教程(图解版)
央企施工企业数字化转型的灵魂是什么
AVL树的插入操作
uni-app覆盖组件样式h5生效,微信小程序不生效的问题
TMin - TMin是否产生溢出
网络——TCP拥塞控制
网络——2021年大题解析
线性表之顺序表
2022年深圳杯数学建模A题代码思路-- 破除“尖叫效应”与“回声室效应”,走出“信息茧房”