1、本程序主要为了展示通过信号量来实现生产者与消费者模型,为了体现代码的逻辑性,代码中主要有各功能实现函数,省略错误判断处理函数等代码。
2、代码:
1 #include <cstdio>
2 #include <cstdlib>
3 #include <cstring>
4 #include <unistd.h>
5 #include <pthread.h>
6 #include <semaphore.h>
7
8 #define NUM 5
9
10 int queue[NUM];
11 sem_t blank_number, product_number;
12
13 void *producer(void *arg)
14 {
15 int i = 0;
16
17 while(1){
18 sem_wait(&blank_number);
19 queue[i] = rand()%1000+1;
20 printf("-----produce---%d\n", queue[i]);
21 sem_post(&product_number);
22
23 i = (i+1) % NUM;
24 sleep(rand() % 2);
25 }
26
27 return NULL;
28 }
29
30 void *consumer(void *arg)
31 {
32 int i = 0;
33
34 while(1){
35 sem_wait(&product_number);
36 printf("--consume---%d\n", queue[i]);
37 queue[i] = 0;
38 sem_post(&blank_number);
39
40 i = (i+1) % NUM;
41 sleep(rand()%3);
42 }
43
44 return NULL;
45 }
46
47 int main(int argc, char *argv[])
48 {
49 srand(time(NULL));
50 pthread_t pid, cid;
51
52 sem_init(&blank_number, 0, NUM);
53 sem_init(&product_number, 0, 0);
54
55 pthread_create(&pid, NULL, producer, NULL);
56 pthread_create(&cid, NULL, consumer, NULL);
57
58 pthread_join(pid, NULL);
59 pthread_join(cid, NULL);
60
61 sem_destroy(&blank_number);
62 sem_destroy(&product_number);
63
64 return 0;
65 }