-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11_conditional_broadcast.c
61 lines (56 loc) · 1.65 KB
/
11_conditional_broadcast.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
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
pthread_mutex_t mutexFuel;
pthread_cond_t condFuel;
int fuel = 0;
void* fuel_filling(void* arg) {
for (int i = 0; i < 5; i++) {
pthread_mutex_lock(&mutexFuel);
fuel += 30;
printf("Filled fuel... %d\n", fuel);
pthread_mutex_unlock(&mutexFuel);
pthread_cond_broadcast(&condFuel);
sleep(1);
}
}
void* car(void* arg) {
pthread_mutex_lock(&mutexFuel);
while (fuel < 40) {
printf("No fuel. Waiting...\n");
pthread_cond_wait(&condFuel, &mutexFuel);
// Equivalent to:
// pthread_mutex_unlock(&mutexFuel);
// wait for signal on condFuel
// pthread_mutex_lock(&mutexFuel);
}
fuel -= 40;
printf("Got fuel. Now left: %d\n", fuel);
pthread_mutex_unlock(&mutexFuel);
}
int main(int argc, char* argv[]) {
pthread_t th[6];
pthread_mutex_init(&mutexFuel, NULL);
pthread_cond_init(&condFuel, NULL);
for (int i = 0; i < 6; i++) {
if (i == 4 || i == 5) {
if (pthread_create(&th[i], NULL, &fuel_filling, NULL) != 0) {
perror("Failed to create thread");
}
} else {
if (pthread_create(&th[i], NULL, &car, NULL) != 0) {
perror("Failed to create thread");
}
}
}
for (int i = 0; i < 6; i++) {
if (pthread_join(th[i], NULL) != 0) {
perror("Failed to join thread");
}
}
pthread_mutex_destroy(&mutexFuel);
pthread_cond_destroy(&condFuel);
return 0;
}