-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise-A.c
85 lines (66 loc) · 1.76 KB
/
exercise-A.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
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h> /* printf(), fprintf */
#include <stdlib.h> /* [s]rand() */
#include <unistd.h> /* sleep() */
#include <pthread.h> /* pthread_... */
#define PRODUCERS 10
#define CONSUMERS 10
int done = 0;
int count = 0;
static pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t consumer_tid[CONSUMERS], producer_tid[PRODUCERS];
void *
producer(void *param)
{
long int id = (long int)param;
pthread_mutex_lock(&mutex);
count = count + 1;
printf("Producer: thread_id: %2d count: %2d\n", id+1, count);
if ( count == 10 ){
pthread_cond_broadcast(&cond);
done = 1;
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *
consumer(void *param)
{
long int id = (long int)param;
pthread_mutex_lock(&mutex);
while ( done != 1 )
pthread_cond_wait(&cond, &mutex);
printf("Consumer: thread_id: %2d count: %2d\n", id+11, count);
count = count - 1;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int
main()
{
long int i;
/* Create the producer threads */
for (i = 0; i < PRODUCERS; i++)
if (pthread_create(&producer_tid[i], NULL, producer, (void *)i) != 0) {
perror("producer: pthread_create");
abort();
}
/* Create the consumer threads */
for (i = 0; i < CONSUMERS; i++)
if (pthread_create(&consumer_tid[i], NULL, consumer, (void *)i) != 0) {
perror("consumer: pthread_create");
abort();
}
/* Wait for them to complete */
for (i = 0; i < PRODUCERS; i++)
if (pthread_join(producer_tid[i], NULL) != 0) {
perror("producer: pthread_join");
abort();
}
for (i = 0; i < CONSUMERS; i++)
if (pthread_join(consumer_tid[i], NULL) != 0) {
perror("consumer: pthread_join");
abort();
}
return 0;
}