-
Notifications
You must be signed in to change notification settings - Fork 4
/
producer.c
73 lines (61 loc) · 1.53 KB
/
producer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
The producer-consumer problem using pthreads
compile with: cc -lpthread
*/
#include <stdio.h>
#include <pthread.h>
#define MAX 10
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void *producer (void *ptr)
{
int i;
for (i = 1; i <= MAX; ++i)
{
pthread_mutex_lock (&the_mutex); /* critical region access */
while (buffer != 0) /* no need to produce, sleep */
{
pthread_cond_wait (&condp, &the_mutex);
}
buffer = i;
printf ("producing %d\n", buffer);
pthread_cond_signal (&condc); /* wake up the consumer */
pthread_mutex_unlock (&the_mutex);
}
puts ("end of producer");
pthread_exit (0);
}
void *consumer (void *ptr)
{
int i;
for (i = 1; i <= MAX; ++i)
{
pthread_mutex_lock (&the_mutex); /* critical region access */
while (buffer == 0) /* nothing to consume, sleep... */
{
pthread_cond_wait (&condc, &the_mutex);
}
buffer = 0;
printf ("consuming %d\n", i);
pthread_cond_signal (&condp); /* wake up the producer */
pthread_mutex_unlock (&the_mutex);
}
puts ("end of consumer");
pthread_exit (0);
}
int main (void)
{
pthread_t pro, con;
pthread_mutex_init (&the_mutex, 0);
pthread_cond_init (&condc, 0);
pthread_cond_init (&condp, 0);
pthread_create (&con, 0, consumer, 0);
pthread_create (&pro, 0, producer, 0);
pthread_join (pro, 0);
pthread_join (con, 0);
pthread_cond_destroy (&condc);
pthread_cond_destroy (&condp);
pthread_mutex_destroy (&the_mutex);
return 0;
}