Logo AND Algorithmique Numérique Distribuée

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