Commit | Line | Data |
---|---|---|
91265850 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 | #define libre 1 | |
14 | #define occupe 0 | |
a2b1260f | 15 | static int fourch[N] = { libre, libre, libre, libre, libre }; |
91265850 JB |
16 | |
17 | sem_t mutex; | |
18 | ||
19 | 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); | |
4db9379b | 54 | printf("fin des threads\n"); |
91265850 JB |
55 | return 0; |
56 | } |