当前位置:网站首页>生产者-消费者线程模型学习
生产者-消费者线程模型学习
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;
}
边栏推荐
- 苹果开发者账号 申请 D-U-N-S 编号
- uniapp 项目搭建
- HR to get the entry date RP_GET_HIRE_DATE
- How to create DataFrame with feature importance from XGBClassifier made by GridSearchCV?
- Codeforces Round #808 (Div. 2)||Precipitation
- 国星光电吉利产业园项目主体结构全面封顶,将重点生产 RGB 小间距、Mini LED、TOP LED 等产品
- std::uniform_real_distribution的一个bug引发的服务器崩溃
- 网络——局域网和广域网
- No need to pay for the 688 Apple developer account, xcode13 packaged and exported ipa, and provided others for internal testing
- MySQL 5.5系列安装步骤教程(图解版)
猜你喜欢
随机推荐
网络——IPV4地址(二)
一个程序员的水平能差到什么程度?
MySQL 5.5 series installation steps tutorial (graphical version)
Leetcode 算法面试冲刺 热题 HOT 100 刷题(406 416 437 438 448)(六十九)
The use of websocket in uni-app Disconnection, reconnection, heartbeat mechanism
七.getchar 和 scanf
3种特征分箱方法!
现在,怎么挑选舞台租赁LED显示屏?
网络——涉及的相关协议和设备汇总
网络——IPv6(一)
B024 – STM32温湿度控制体温检测烟雾报警系统
QT工程编译过程学习
Reasons for slow startup of IDEA (1)
Leading practice | How the world's largest wine app uses design sprint to innovate the vivino model
第一篇博客
A48基于NRF24L01的无线心率血氧体温检测
Numpy数组索引/切片 多维度索引
shopee引流方式有哪些,商家如何为自己店铺做引流?
良匠-手把手教你写NFT抢购软(三)
零基础爬虫regex练习「音乐抓取」









