Remove a variable shadowing warning.
[TD_SE.git] / philosophe-famine / philosophe.c
CommitLineData
fa1b4804
JB
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
17static int phiState[N] = { penser };
18
19sem_t mutex;
20sem_t semPhil[N];
21
22void 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
31void *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
62int main()
63{
64 int i, NumPhi[N] = { 0, 1, 2, 3, 4 };
65 pthread_t th[N];
66 sem_init(&mutex, 0, 1);
e2317121 67 for (i = 0; i < N; i++) {
fa1b4804
JB
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}