Remove a variable shadowing warning.
[TD_SE.git] / philosophe-famine / 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
14 #define penser 0
15 #define faim 1
16 #define manger 2
17 static int phiState[N] = { penser };
18
19 sem_t mutex;
20 sem_t semPhil[N];
21
22 void test(int i)
23 {
24 if (phiState[i] == faim && phiState[G] != manger
25 && phiState[D] != manger) {
26 phiState[i] = manger;
27 sem_post(&semPhil[i]);
28 }
29 }
30
31 void *philosophe(void *num)
32 {
33 int i = *(int *)num, nb = 2;
34 while (nb) {
35 /* penser */
36 sem_wait(&mutex);
37 phiState[i] = penser;
38 sem_post(&mutex);
39 sleep(1);
40 /* essayer de manger */
41 sem_wait(&mutex);
42 phiState[i] = faim;
43 test(i);
44 sem_post(&mutex);
45 /* attendre son tour */
46 sem_wait(&semPhil[i]);
47 /* à nous de manger */
48 printf("philosophe[%d] mange\n", i);
49 sleep(1);
50 printf("philosophe[%d] a fini\n", i);
51 /* laisser manger ses voisins */
52 sem_wait(&mutex);
53 phiState[i] = penser;
54 test(G);
55 test(D);
56 sem_post(&mutex);
57 nb--;
58 }
59 return NULL;
60 }
61
62 int main()
63 {
64 int i, NumPhi[N] = { 0, 1, 2, 3, 4 };
65 pthread_t th[N];
66 sem_init(&mutex, 0, 1);
67 for (i = 0; i < N; i++) {
68 sem_init(&semPhil[i], 0, 1);
69 }
70 // création des N philosophes
71 for (i = 0; i < N; i++)
72 pthread_create(&th[i], NULL, philosophe, &NumPhi[i]);
73 // attendre la fin des threads
74 for (i = 0; i < N; i++)
75 pthread_join(th[i], NULL);
76 printf("fin des threads\n");
77 return 0;
78 }