22923ceda26bc18858965e61823371811e2714af
[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] = { libre };
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] = { 0, 1, 2, 3, 4 };
46 pthread_t th[N];
47 sem_init(&mutex, 0, 1);
48 // création des N philosophes
49 for (i = 0; i < N; i++)
50 pthread_create(&th[i], NULL, philosophe, &NumPhi[i]);
51 // attendre la fin des threads
52 for (i = 0; i < N; i++)
53 pthread_join(th[i], NULL);
54 printf("fin des threads\n");
55 return 0;
56 }