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