问题描述:
思路:
代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
#define maxsize 10
int product[maxsize]={0};
sem_t empty,full,mutex;
int in,out;
void *producer_i(void *arg){
while(1)
{
sleep(1);
sem_wait(&empty);
sem_wait(&mutex);
product[in]=1;
printf("生产者将一个产品放入缓冲区 ");
printf("缓冲区产品现况:");
for(int i=0;i<maxsize;i++)
{
printf("%d ",product[i]);
}
printf("\n");
in=(in+1)%maxsize;
sem_post(&mutex);
sem_post(&full);
}
}
void *consumer_j(void *arg){
while(1){
sem_wait(&full);
sem_wait(&mutex);
product[out]=0;
printf("消费者从缓冲区取走一个产品 ");
out=(out+1)%maxsize;
printf("缓冲区产品现况:");
for(int i=0;i<maxsize;i++)
{
printf("%d ",product[i]);
}
printf("\n");
sem_post(&mutex);
sem_post(&empty);
sleep(2);
}
}
int main()
{
in=0;
out=0;
int sg1,sg2,sg3;
pthread_t producer1,producer2,consumer;
sg1=sem_init(&empty,0,maxsize);
sg2=sem_init(&full,0,0);
sg3=sem_init(&mutex,0,1);
pthread_create(&producer1,NULL,(void *)producer_i,NULL);
pthread_create(&producer2,NULL,(void *)producer_i,NULL);
pthread_create(&consumer,NULL,(void *)consumer_j,NULL);
pthread_join(producer1,NULL);
pthread_join(producer2,NULL);
pthread_join(consumer,NULL);
return 0;
}
运行截图