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

一.线程同步的概念

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

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

  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);
	}
}

请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值