思路:
代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
sem_t empty,full;
void *producer_i(void *arg){
while(1){
sleep(1);
sem_wait(&empty);
printf("缓冲区有产品\n");
sem_post(&full);
}
}
void *consumer_j(void *arg){
while(1){
sem_wait(&full);
printf("缓冲区无产品\n");
sem_post(&empty);
sleep(2);
}
}
int main(){
int sg1,sg2;
pthread_t producer1,producer2,consumer;
sg1=sem_init(&empty,0,1);
sg2=sem_init(&full,0,0);
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;
}
运行截图