当前位置: 首页 > news >正文

线程同步:消费者模型(非常重要的模型)

一.线程同步的概念

  • 线程同步:是指在互斥的基础上,通过其它机制实现访问者对 资源的有序访问。
  • 条件变量:线程库提供的专门针对线程同步的机制
  • 线程同步比较典型的应用场合就是 生产者与消费者

二、生产者与消费者模型原理

  1. 在这个模型中,包括生产者线程与消费者线程。通过线程来模拟多个线程同步的过程
  2. 在这个模型中,需要以下组件
  • 仓库 : 用于存储产品,一般作为共享资源
  • 生产者线程 : 用于生产产品
  • 消费者线程 : 用于消费产品
  1. 原理
  • 当仓库没有产品时,则消费者线程需要等待,直到有产品时才能消费
  • 当仓库已经装满产品时,则生产者线程需要等待,直到消费者线程消费产品之后

在这里插入图片描述

三、生产者与消费者模型同步

using namespace std;
#include<iostream>
#include<string>
#include<vector>
#include<deque>
#include<ctime>
#include<deque>
#include<cstdlib>
#include<pthread.h>
#include <unistd.h>
int production = 0;
//静态互斥锁
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//线程生产函数 
void * start_routinue(void* arg){int nsems = atoi((char*)arg);for(int i = 0;i < nsems;i++){pthread_mutex_lock(&mutex);production++;cout << pthread_self() << "生产了" <<  production << endl;sleep(1);  pthread_mutex_unlock(&mutex);}pthread_exit(NULL);
}
//主函数 
int main(int argc,char* argv[]){if(argc < 2){cout << "error" << endl;exit(EXIT_FAILURE);}cout << argc  << endl;int total_production = 0;int total_resumption = 0;vector<pthread_t> arr;for(int i = 1;i < argc;i++){arr.push_back(i);}for(int i = 0;i < arr.size();i++){total_production += atoi(argv[i + 1]);int ret = pthread_create(&(arr.at(i)),NULL,start_routinue,(void*)argv[i + 1]);if(ret != 0){cout << "create failed" << endl;exit(EXIT_FAILURE);}}//线程消费while(1){pthread_mutex_lock(&mutex);while(production > 0){total_resumption++;production--;cout << pthread_self() <<  "消费了" << endl;sleep(1);}if(total_resumption == total_production){break;}pthread_mutex_unlock(&mutex);}
}

请添加图片描述


http://www.mrgr.cn/news/34463.html

相关文章:

  • STM32之串口通信
  • 【C++篇】走进C++标准模板库:STL的奥秘与编程效率提升之道
  • Redis:持久化
  • pyqt QGraphicsView 以鼠标为中心进行缩放
  • 2024年9月24日 十二生肖 今日运势
  • 高通Android 12 push framework.jar和service.jar
  • 解决跨域问题的方法
  • WinCC中归档数据片段的时间和尺寸设置
  • 深度学习:卷积神经网络(CNN)基础知识
  • WordPress精选文章如何添加侧边栏和页面?
  • 华为三折叠一拆,苹果脸被打肿了!
  • c++ 类中特殊成员函数
  • 【C++】10道经典面试题带你玩转二叉树
  • 后端开发刷题 | 没有重复项数字的全排列
  • 【学术会议征稿】第七届电力电子与控制工程国际学术会议(ICPECE 2024)
  • Nginx作用
  • 在Android开发中可以用到的Ui控件有哪些?
  • Ubuntu 升级特定软件包
  • 【洛谷】P10417 [蓝桥杯 2023 国 A] 第 K 小的和 的题解
  • 《深度学习》—— 神经网络中常用的激活函数