Make some array initializations variable.
[TD_SE.git] / philosophe / philosophe.c
1 // programme philosophe.c
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <pthread.h>
5 #include <semaphore.h>
6
7 #define N 5
8 // nombre de philosophes
9 #define G (i + 1) % N
10 // fourchette gauche du philosophe i
11 #define D i
12 // fourchette droite du philosophe i
13 #define libre 1
14 #define occupe 0
15 static int fourch[N];
16
17 sem_t mutex;
18
19 static void *philosophe(void *num)
20 {
21 int i = *(int *)num, nb = 2;
22 while (nb) {
23 sleep(1); // penser
24 sem_wait(&mutex); // essayer de prendre les fourchettes pour manger
25 if (fourch[G] == libre && fourch[D] == libre) {
26 fourch[G] = occupe;
27 fourch[D] = occupe;
28 sem_post(&mutex);
29 nb--;
30 printf("philosophe[%d] mange\n", i);
31 sleep(1); // manger
32 printf("philosophe[%d] a fini de manger\n", i);
33 sem_wait(&mutex); // libérer les fourchettes
34 fourch[G] = libre;
35 fourch[D] = libre;
36 sem_post(&mutex);
37 } else
38 sem_post(&mutex);
39 }
40 return NULL;
41 }
42
43 int main()
44 {
45 int i, NumPhi[N];
46 for (i = 0; i < N; i++)
47 NumPhi[i] = i;
48 for (i = 0; i < N; i++)
49 fourch[i] = libre;
50 pthread_t th[N];
51 sem_init(&mutex, 0, 1);
52 // création des N philosophes
53 for (i = 0; i < N; i++)
54 pthread_create(&th[i], NULL, philosophe, &NumPhi[i]);
55 // attendre la fin des threads
56 for (i = 0; i < N; i++)
57 pthread_join(th[i], NULL);
58 printf("fin des threads\n");
59 return 0;
60 }