-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdining-professors.c
73 lines (56 loc) · 1.93 KB
/
dining-professors.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
/*
My solution for the famous Dining Professors problem
which avoids deadlocks and starvation by getting help from Mutexes
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t chopsticks[5];
struct professor {
int id;
};
void* dine(void* params) {
struct professor *args = (struct professor*) params;
unsigned int professorID = args->id;
while (1) {
printf("Professor %d: thinking\n", professorID);
sleep(rand() % 5 + 1);
printf("Professor %d: trying to get left chopstick\n", professorID);
pthread_mutex_lock(&chopsticks[professorID]);
printf("Professor %d: got left chopstick\n", professorID);
if (pthread_mutex_trylock(&chopsticks[(professorID + 1) % 5]) != 0) {
printf("Professor %d: could not get right chopstick, putting down left chopstick\n", professorID);
pthread_mutex_unlock(&chopsticks[professorID]);
sleep(rand() % 5 + 1);
continue;
}
printf("Professor %d: got both chopsticks, eating\n", professorID);
sleep(rand() % 6 + 5);
pthread_mutex_unlock(&chopsticks[(professorID + 1) % 5]);
pthread_mutex_unlock(&chopsticks[professorID]);
printf("Professor %d: finished eating and put down both chopsticks\n", professorID);
}
return NULL;
}
int main() {
srand(time(NULL));
pthread_t* professors = malloc(5 * sizeof(pthread_t));
struct professor* args;
for (int i = 0; i < 5; i++) {
pthread_mutex_init(&chopsticks[i], NULL);
}
for (int i = 0; i < 5; i++) {
args = malloc(sizeof(struct professor));
args->id = i;
pthread_create(&(professors[i]), NULL, dine, (void*)args);
}
for (int i = 0; i < 5; i++) {
pthread_join(professors[i], NULL);
}
for (int i = 0; i < 5; i++) {
pthread_mutex_destroy(&chopsticks[i]);
}
free(professors);
return 0;
}