多线程生产者和消费者

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <unistd.h>
#include <iostream>

using namespace std;

const int ConsumerNum = 3;
const int PruducterNum = 2;

const int M = 20;//缓存区大小

int in = 0;
int out = 0;

int buff[M] = {0};

sem_t empty_sem;//表示空位的数量
sem_t full_sem;//产品的数量

pthread_mutex_t mutex;//线程在读取或产生时,都应该加锁
int i=0;//产品Id

void *product(void *)
{
	while (true)
	{
		//sleep(1);
		sem_wait(&empty_sem);//空位数减1,已经把这个位置站住了,其他线程只能访问剩余位置
		pthread_mutex_lock(&mutex);
		cout<<"producter "<<pthread_self()<<" produce "<<i<<endl;
		buff[in] = i++;
		in = (in+1)%M;
		pthread_mutex_unlock(&mutex);
		sem_post(&full_sem);//产品数加1

	}
}

void *consumer(void *)
{
	while(true)
	{
		//sleep(1);
		sem_wait(&full_sem);
		pthread_mutex_lock(&mutex);
		cout<<"consumer "<<pthread_self()<<" consume "<<buff[out]<<endl;
		out = (out+1)%M;
		pthread_mutex_unlock(&mutex);
		sem_post(&empty_sem);
	}
}

int main(void)
{
	pthread_t consumers[ConsumerNum];
	pthread_t producters[PruducterNum];

	sem_init(&empty_sem,0,M);//设初始值为M
	sem_init(&full_sem,0,0);//初始值为0

	pthread_mutex_init(&mutex,NULL);

	for (int ind=0;ind<ConsumerNum;++ind)
	{
		pthread_create(&consumers[ind],NULL,consumer,(void *)NULL);
	}
	for (int ind=0;ind<PruducterNum;++ind)
	{
		pthread_create(&producters[ind],NULL,product,(void *)NULL);
	}

	for(int ind =0;ind<ConsumerNum;++ind)
		pthread_join(consumers[ind],NULL);

	for(int ind = 0;ind <PruducterNum;++ind)
		pthread_join(producters[ind],NULL);
	
	exit(0);
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值