生产者与消费者

#include<list>
#include<stdio.h>
#include<pthread.h>
#include <semaphore.h>
#include <iostream>
using namespace std;
sem_t mutex;
sem_t fillCount;
sem_t emptyCount;
list <int> l;
int x;
pthread_t thread[2];
void *producer(void *);
void *consumer(void *);
int main()
{
	sem_init(&mutex,0,1);
	sem_init(&fillCount,0,0);
	sem_init(&emptyCount,0,3);
	void *p;
	pthread_create(&thread[0],NULL,producer,NULL);
	pthread_create(&thread[1],NULL,consumer,NULL);
	pthread_join(thread[0],&p);
	pthread_join(thread[1],&p);

}

void *producer(void *) {
	int i=0;
	while (true) {
		sem_wait(&emptyCount);
		sem_wait(&mutex);//emptycount和mutex的顺序不能对调
		//printf("producer done\n");
		sleep(1);
		l.push_back(i);
		i++;
		sem_post(&mutex);
		sem_post(&fillCount);

		//printf("prove\n");


	}
	return NULL;
}
void *consumer(void *) {
	while (true) {
		sem_wait(&fillCount);
		sem_wait(&mutex);
		x=l.front();
		l.pop_front();
		printf("%d\n",x);
		//printf("consumer done\n");
		sleep(1);
		sem_post(&mutex);
		sem_post(&emptyCount);


		//  printf("cous\n");


	}
	return NULL;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值