以下是一对一的关系;(还有一对多,多对一,多对多的关系);
以下为代码:
1 #include<stdio.h>
2 #include<unistd.h>
3 #include<pthread.h>
4 #include<stdlib.h>
5 #include<string.h>
6
7 #define MAX_PRODUCER_THREAD_SIZE 3
8 #define MAX_CONSUMER_THREAD_SIZE 1
9 #define MAX_COUNT 20
10
11 #define BUFFER_SIZE 8
12 #define OVER_DATA -1
13
14 struct pcst
15 {
16 pthread_mutex_t mutex;
17 pthread_cond_t not_full;
18 pthread_cond_t not_empty;
19 int buffer[BUFFER_SIZE];
20 int write_pos;
21 int read_pos;
22 int nvalue;
23 }shared = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND _INITIALIZER};
24
25 void init_pcst(struct pcst *pc)
26 {
27 memset(pc->buffer, 0, sizeof(pc->buffer));
28 pc->write_pos = 0;
29 pc->read_pos = 0;
30 pc->nvalue = 1;
31 }
32
33 void put_data(struct pcst *pc, int value)
34 {
35 pthread_mutex_lock(&pc->mutex);
36 //
37 if((pc->write_pos+1)%BUFFER_SIZE == pc->read_pos)
38 pthread_cond_wait(&pc->not_full, &pc->mutex);
39
40 pc->buffer[pc->write_pos] = value;
41 pc->write_pos++;
42 pc->write_pos %= BUFFER_SIZE;
43
44 pthread_cond_signal(&pc->not_empty);
45
46 pthread_mutex_unlock(&pc->mutex);
47 }
48
49
50 void* producer(void *arg)
51 {
52 int i;
53 for(i=0; i<MAX_COUNT; ++i)
54 {
55 put_data(&shared, shared.nvalue);
56 shared.nvalue++;
57 }
58 //printf("produce finish.\n");
59 //put_data(&shared, OVER_DATA);
60 }
61 int get_data(struct pcst *pc)
62 {
63 pthread_mutex_lock(&pc->mutex);
64
65 if(pc->read_pos == pc->write_pos)
66 pthread_cond_wait(&pc->not_empty, &pc->mutex);
67
68 int data = pc->buffer[pc->read_pos];
69 pc->read_pos++;
70 pc->read_pos %= BUFFER_SIZE;
71
72 pthread_cond_signal(&pc->not_full);
73
74 pthread_mutex_unlock(&pc->mutex);
75 return data;
76 }
77 void* consumer(void *arg)
78 {
79 int value;
80 while(1)
81 {
82 value = get_data(&shared);
83
84 //if(value == OVER_DATA)
85 if(value > MAX_COUNT)
86 break;
87 printf("value = %d\n",value);
88 sleep(1);
89 }
90 }
91
92 int main()
93 {
94 init_pcst(&shared);
95
96 pthread_t pro_tid[MAX_PRODUCER_THREAD_SIZE];
97 pthread_t con_tid[MAX_CONSUMER_THREAD_SIZE];
98
99 int i;
100 for(i=0; i<MAX_PRODUCER_THREAD_SIZE; ++i)
101 {
102 pthread_create(&pro_tid[i], NULL, producer, NULL);
103 // pthread_create(&con_tid[i], NULL, consumer, NULL);
104 }
105 for(i=0; i<MAX_CONSUMER_THREAD_SIZE; ++i)
106 {
107 pthread_create(&con_tid[i], NULL, consumer, NULL);
108 }
109
for(i=0; i<MAX_PRODUCER_THREAD_SIZE; ++i)
111 {
112 pthread_join(pro_tid[i],NULL);
113 }
114 for(i=0; i<MAX_CONSUMER_THREAD_SIZE; ++i)
115 {
116 pthread_join(con_tid[i], NULL);
117 }
118
119 return 0;
120 }
121