-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20_recursive_mutex.c
49 lines (44 loc) · 1.38 KB
/
20_recursive_mutex.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
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define THREAD_NUM 8
pthread_mutex_t mutexFuel;
int fuel = 50;
void* routine(void* args) {
pthread_mutex_lock(&mutexFuel);
pthread_mutex_lock(&mutexFuel);
pthread_mutex_lock(&mutexFuel);
pthread_mutex_lock(&mutexFuel);
pthread_mutex_lock(&mutexFuel);
fuel += 50;
printf("Incremented fuel to %d\n", fuel);
pthread_mutex_unlock(&mutexFuel);
pthread_mutex_unlock(&mutexFuel);
pthread_mutex_unlock(&mutexFuel);
pthread_mutex_unlock(&mutexFuel);
pthread_mutex_unlock(&mutexFuel);
}
int main(int argc, char *argv[]) {
pthread_t th[THREAD_NUM];
pthread_mutexattr_t recursiveMutexAttributes;
pthread_mutexattr_init(&recursiveMutexAttributes);
pthread_mutexattr_settype(&recursiveMutexAttributes, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutexFuel, &recursiveMutexAttributes);
int i;
for (i = 0; i < THREAD_NUM; i++) {
if (pthread_create(&th[i], NULL, &routine, NULL) != 0) {
perror("Failed to create thread");
}
}
for (i = 0; i < THREAD_NUM; i++) {
if (pthread_join(th[i], NULL) != 0) {
perror("Failed to join thread");
}
}
printf("Fuel: %d\n", fuel);
pthread_mutexattr_destroy(&recursiveMutexAttributes);
pthread_mutex_destroy(&mutexFuel);
return 0;
}