1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4 #include <pthread.h>
5
6 #define BUFFER_SIZE 2
7 struct prodcons
8 {
9 int buffer[BUFFER_SIZE];
10 pthread_mutex_t lock;
11 int readpos,writepos;
12 pthread_cond_t notempty;
13 pthread_cond_t notfull;
14 };
15
16 void init(struct prodcons *prod)
17 {
18 pthread_mutex_init(&prod->lock,NULL);
19 pthread_cond_init(&prod->notempty,NULL);
20 pthread_cond_init(&prod->notfull,NULL);
21 prod->readpos=0;
22 prod->writepos=0;
23 }
24
25 void put(struct prodcons *prod, int data)
26 {
27 pthread_mutex_lock(&prod->lock);
28 while((prod->writepos+1)%BUFFER_SIZE==prod->readpos)
29 {
30 printf("producer wait for not full\n");
31 pthread_cond_wait(&prod->notfull,&prod->lock);
32 }
33 prod->buffer[prod->writepos]=data;
34 prod->writepos++;
35 if(prod->writepos>=BUFFER_SIZE)
36 prod->writepos=0;
37 pthread_cond_signal(&prod->notempty);
38 pthread_mutex_unlock(&prod->lock);
39 }
40
41 int get(struct prodcons *prod)
42 {
43 int data;
44 pthread_mutex_lock(&prod->lock);
45 while(prod->writepos==prod->readpos)
46 {
47 printf("consumer wait for not empty\n");
48 pthread_cond_wait(&prod->notempty,&prod->lock);
49 }
50 data=prod->buffer[prod->readpos];
51 prod->readpos++;
52 if(prod->readpos>=BUFFER_SIZE)
53 prod->readpos=0;
54 pthread_cond_signal(&prod->notfull);
55 pthread_mutex_unlock(&prod->lock);
56 return data;
57 }
58
59 #define OVER (-1)
60
61 struct prodcons buffer;
62
63 void *producer(void * data)
64 {
65 int n;
66 for(n=1;n<=5;n++)
67 {
68 printf("producer sleep 1 second...\n");
69 sleep(1);
70 printf("put the %d product\n",n);
71 put(&buffer,n);
72 }
73 for(n=6;n<=10;n++)
74 {
75 printf("producer sleep 3 second...\n");
76 sleep(3);
77 printf("put the %d product\n",n);
78 put(&buffer,n);
79 }
80 put(&buffer,OVER);
81 printf("producer stopped\n");
82 return NULL;
83 }
84
85 void *consumer(void *data)
86 {
87 int d=0;
88 while(1)
89 {
90 printf("consumer sleep 2 second...\n");
91 sleep(2);
92 d=get(&buffer);
93 printf("get the %d product\n",d);
94 if(d==OVER)
95 break;
96 }
97 printf("consumer stopped\n");
98 return NULL;
99 }
100
101 int main(int argc, char *argv[])
102 {
103 pthread_t th_a,th_b;
104 void *retval;
105 init(&buffer);
106 pthread_create(&th_a,NULL,producer,0);
107 pthread_create(&th_b,NULL,consumer,0);
108 pthread_join(th_a,&retval);
109 pthread_join(th_b,&retval);
110 return 0;
111 }