1 //生产者和消费者问题
2 //使用环形队列
3 //解决了生产过剩的问题
4 #include <stdio.h>
5 #include <semaphore.h>
6 #include <pthread.h>
7 #include <stdlib.h>
8 #include <time.h>
9 #include <unistd.h>
10
11 //定义环形队列类型
12 #define Q_MAX 7
13 typedef int queue_t[Q_MAX];
14 queue_t que;//定义一个环状队列
15 sem_t p,c;//可生产的数量和可消费的数量
16
17 //生产者线程
18 void *product(void*arg){
19 int rear=0;
20 while(1){
21 sem_wait(&p);//p--
22 que[rear]=rand()%1000+1;
23 printf("p:%d\n",que[rear]);
24 rear=(rear+1)%Q_MAX;
25 sem_post(&c);//c++
26 sleep(rand()%5+1);
27 }
28 }
29 //消费者线程
30 void *consume(void*arg){
31 int front=0;
32 int tmp;
33 while(1){
34 sem_wait(&c);//c--
35 tmp=que[front];
36 que[front]=-1;
37 printf("c:%d\n",tmp);
38 front=(front+1)%Q_MAX;
39 sem_post(&p);//p++
40 sleep(rand()%5+1);
41 }
42 }
43
44 int main(){
45 srand(time(NULL));
46 //初始化信号量p c
47 sem_init(&p,0,Q_MAX);
48 sem_init(&c,0,0);
49
50 pthread_t pid,cid;
51 //创建两个线程 pid生产者;cid消费者
52 pthread_create(&pid,NULL,product,NULL);
53 pthread_create(&cid,NULL,consume,NULL);
54
55 //阻塞等待线程汇合
56 pthread_join(pid,NULL);
57 pthread_join(cid,NULL);
58
59 //销毁信号量
60 sem_destroy(&p);
61 sem_destroy(&c);
62 return 0;
63 }