/* 生产者和消费者典型案例 */
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <semaphore.h>
int queue[5];
//sem_p 代表可生产的资源数
//sem_c 可消费的资源数
sem_t sem_p,sem_c;
//用于生产者,生产出来,添加到队列中
void *pro(void *arg){
int p=0;
while(1){
//生产了一个数
//lock sem_p
sem_wait(&sem_p);
queue[p]=rand()%1000+1;
printf("pro %d\n",queue[p]);
//unlock sem_c
sem_post(&sem_c);
p=(p+1)%5;
sleep(rand()%5);
}
return NULL;
}
//用于消费者,从队列中取出数据消费
void *con(void *arg){
int c=0;
while(1){
//lock sem_c
sem_wait(&sem_c);
printf("con %d\n",queue[c]);
queue[c]=0;
//unlock sem_p
sem_post(&sem_p);
c=(c+1)%5;
sleep(rand()%5);
}
return NULL;
}
int main(void){
pthread_t cid,pid;
srand(time(NULL));
//初始化信号量
sem_init(&sem_p,0,5);
sem_init(&sem_c,0,0);
//创建两个线程分别用于生产者和消费者
pthread_create(&cid,NULL,con,NULL);
pthread_create(&pid,NULL,pro,NULL);
//阻塞等待线程的汇合
pthread_join(cid,NULL);
pthread_join(pid,NULL);
//销毁信号量
sem_destroy(&sem_p);
sem_destroy(&sem_c);
return 0;
}