#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
#include <stdio.h>
#define BUFSIZE 5
#define pNUM 5 //生产者数量
#define cNUM 5 //消费者数量
int in=0 , out=0; //生产者指针和消费者指针
//pthread_mutex_t ch_mutex;
sem_t mutex , empty , full; //互斥信号量-缓冲区互斥使用,empty缓冲区中空缓冲区的数量
char nextp;
char buff[BUFSIZE]={'*','*','*','*','*'};
void printfBuff()
{
int i;
for(i=0;i<BUFSIZE;i++) printf("%c",buff[i]);
printf("\n");
}
//生产者
void *producer(void *arg){
int i = 0;
while(i<3){ //每个生产者最多可以对缓冲区操作3次
nextp = 'p';
sem_wait(&empty); //申请一个空缓冲区
sem_wait(&mutex);
buff[in] = nextp;
in = (in+1) % BUFSIZE;
i++;
printf("生产者%ld生产一个p\t",pthread_self());
printfBuff();
sem_post(&mutex);
sem_post(&full);
}
}
//消费者
void *consumer(void *arg){
int i = 0;
while(i<3){ //每个消费者最多可以对缓冲区操作3次
sem_wait(&full);
sem_wait(&mutex);
nextp = buff[out];
buff[out] = '*';
out = (out+1) % BUFSIZE;
i++;
printf("消费者%ld取出一个p\t",pthread_self());
printfBuff();
sem_post(&mutex);
sem_post(&empty);
}
}
int main()
{
printf("BUFSIZE = 5\t");
printfBuff();
sem_init(&mutex,0,1);
sem_init(&empty,0,BUFSIZE);
sem_init(&full,0,0);
pthread_t ptid[pNUM]; //5个生产者
pthread_t ctid[cNUM]; //5个消费者
int i1,j1,i2,j2;
for(i1=0;i1<pNUM;i1++){
pthread_create(&ptid[i1],NULL,producer,&i1);
}
for(i2=0;i2<5;i2++){
pthread_create(&ctid[i2],NULL,consumer,&i2);
}
for(i1=0;i1<pNUM;i1++) pthread_join(ptid[i1],NULL);
for(i2=0;i2<cNUM;i2++) pthread_join(ctid[i2],NULL);
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
}
运行结果