| 1 | // programme philosophe.c |
| 2 | #include <stdio.h> |
| 3 | #include <unistd.h> |
| 4 | #include <pthread.h> |
| 5 | #include <semaphore.h> |
| 6 | |
| 7 | #define N 10 |
| 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]; |
| 18 | |
| 19 | sem_t mutex; |
| 20 | sem_t semPhil[N]; |
| 21 | |
| 22 | static 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 | static 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]; |
| 65 | for (i = 0; i < N; i++) |
| 66 | NumPhi[i] = i; |
| 67 | for (i = 0; i < N; i++) |
| 68 | phiState[i] = penser; |
| 69 | pthread_t th[N]; |
| 70 | sem_init(&mutex, 0, 1); |
| 71 | for (i = 0; i < N; i++) |
| 72 | sem_init(&semPhil[i], 0, 1); |
| 73 | // création des N philosophes |
| 74 | for (i = 0; i < N; i++) |
| 75 | pthread_create(&th[i], NULL, philosophe, &NumPhi[i]); |
| 76 | // attendre la fin des threads |
| 77 | for (i = 0; i < N; i++) |
| 78 | pthread_join(th[i], NULL); |
| 79 | printf("fin des threads\n"); |
| 80 | return 0; |
| 81 | } |