pthread:利用条件变量解决生产者-消费者问题

#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>
#include<vector>
using namespace std;

int cnt = 0,N = 10,front = 0,rear = 0;
vector<int> buff(N);
pthread_mutex_t lock;
sem_t bin_sem;
pthread_cond_t empty,full;

void* proceducer(void* arg){
	int i = 0;
	do{
		pthread_mutex_lock(&lock);
		if(cnt>=N) pthread_cond_wait(&full,&lock);
		cnt++;
		cout<<"Proceducer: "<<rear<<endl;
		rear = (rear+1)%N;
		i++;
		pthread_cond_signal(&empty);
		pthread_mutex_unlock(&lock);
		sleep(1);
	}while(i<15);
	return NULL;
}

void* consumer(void* arg){
	int i = 0;
	do{
		pthread_mutex_lock(&lock);
		if(cnt<=0) pthread_cond_wait(&empty,&lock);
		cnt--;
		cout<<"Consumer: "<<front<<endl;
		front = (front+1)%N;
		i++;
		pthread_cond_signal(&full);
		pthread_mutex_unlock(&lock);
//		sleep(1);
	}while(i<15);
	return NULL;
}

int main(){
	pthread_t threads_ID[2];
	void* exit_status;
	
	pthread_mutex_init(&lock,NULL);
	pthread_cond_init(&empty,NULL);
	pthread_cond_init(&full,NULL);
	
	pthread_create(&threads_ID[0],NULL,proceducer,NULL);
	pthread_create(&threads_ID[1],NULL,consumer,NULL);
	pthread_join(threads_ID[0],&exit_status);
	pthread_join(threads_ID[1],&exit_status);
	
	pthread_mutex_destroy(&lock);
	pthread_cond_destroy(&empty);
	pthread_cond_destroy(&full);
	return 0;
} 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值