Logo AND Algorithmique Numérique Distribuée

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