Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add more tests from McMini
[simgrid.git] / teshsuite / mc / mcmini / philosophers_mutex_deadlock.c
1 // Naive dining philosophers solution, which leads to deadlock.
2
3 #include <stdio.h>
4 #include <unistd.h>
5 #include <pthread.h>
6 #include <stdlib.h>
7
8 int DEBUG = 0;
9
10 struct forks {
11     int philosopher;
12     pthread_mutex_t *left_fork;
13     pthread_mutex_t *right_fork;
14 } *forks;
15
16 static void * philosopher_doit(void *forks_arg) {
17     struct forks *forks = forks_arg;
18     pthread_mutex_lock(forks->left_fork);
19     pthread_mutex_lock(forks->right_fork);
20
21     if(DEBUG) printf("Philosopher %d just ate.\n", forks->philosopher);
22     
23     pthread_mutex_unlock(forks->left_fork);
24     pthread_mutex_unlock(forks->right_fork);
25     return NULL;
26 }
27
28 int main(int argc, char* argv[]) {
29     if(argc != 3){
30         printf("Usage: %s NUM_PHILOSOPHERS DEBUG\n", argv[0]);
31         return 1;
32     }
33
34     int NUM_THREADS = atoi(argv[1]);
35     DEBUG = atoi(argv[2]);
36
37     pthread_t thread[NUM_THREADS];
38     pthread_mutex_t mutex_resource[NUM_THREADS];
39
40     forks = malloc(NUM_THREADS * sizeof(struct forks));
41
42     int i;
43     for (i = 0; i < NUM_THREADS; i++) {
44         pthread_mutex_init(&mutex_resource[i], NULL);
45         forks[i] = (struct forks){i,
46                                   &mutex_resource[i], &mutex_resource[(i+1) % NUM_THREADS]};
47     }
48
49     for (i = 0; i < NUM_THREADS; i++) {
50         pthread_create(&thread[i], NULL, &philosopher_doit, &forks[i]);
51     }
52
53     for (i = 0; i < NUM_THREADS; i++) {
54         pthread_join(thread[i], NULL);
55     }
56
57     free(forks);
58     return 0;
59 }