Repository navigation
Expand file tree
/
Copy pathpthread-8.c
More file actions
66 lines (61 loc) · 1.51 KB
/
Copy pathpthread-8.c
File metadata and controls
66 lines (61 loc) · 1.51 KB
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
/*
* mutex and condition example, signaling for condition variables
*/
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
int fuel=0;
pthread_mutex_t mutex_fuel;
pthread_cond_t cond_fuel;
void* fuel_filling(void* arg){
for(int i=0;i<5;i++){
pthread_mutex_lock(&mutex_fuel);
fuel+=30;
printf("filling fuel... %d\n", fuel);
pthread_mutex_unlock(&mutex_fuel);
//pthread_cond_signal(&cond_fuel); //send signal for one car
pthread_cond_broadcast(&cond_fuel); //broadcast the cond signal for all the cars
sleep(1);
}
}
void* car(void* arg){
pthread_mutex_lock(&mutex_fuel);
while(fuel<40){
printf("no fuel, waiting...\n");
pthread_cond_wait(&cond_fuel, &mutex_fuel);
//equivalent to:
//pthread_mutex_unlock(mutex_fuel);
//wait for signal on cond_fuel
//pthread_mutex_lock(&mutex_fuel);
}
fuel-=40;
printf("got fuel, now left: %d\n", fuel);
pthread_mutex_unlock(&mutex_fuel);
}
int main(int argc, char * argv[]){
pthread_t th[6];
pthread_mutex_init(&mutex_fuel, NULL);
pthread_cond_init(&cond_fuel, 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(&mutex_fuel);
pthread_cond_destroy(&cond_fuel);
return 0;
}