X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=philosophe%2Fphilosophe.c;fp=philosophe%2Fphilosophe.c;h=72b740ed762370407ce8f6334fc0f9dc2b7ac04c;hb=912658502558d4881fceed04e0fdda7574f4af13;hp=0000000000000000000000000000000000000000;hpb=66c9107fcb99df4eec36a84db41f78eb946cc224;p=TD_SE.git diff --git a/philosophe/philosophe.c b/philosophe/philosophe.c new file mode 100644 index 0000000..72b740e --- /dev/null +++ b/philosophe/philosophe.c @@ -0,0 +1,56 @@ +// programme philosophe.c +#include +#include +#include +#include + +#define N 5 +// nombre de philosophes +#define G (i + 1) % N +// fourchette gauche du philosophe i +#define D i +// fourchette droite du philosophe i +#define libre 1 +#define occupe 0 +int fourch[N] = { libre, libre, libre, libre, libre }; + +sem_t mutex; + +void *philosophe(void *num) +{ + int i = *(int *)num, nb = 2; + while (nb) { + sleep(1); // penser + sem_wait(&mutex); // essayer de prendre les fourchettes pour manger + if (fourch[G] == libre && fourch[D] == libre) { + fourch[G] = occupe; + fourch[D] = occupe; + sem_post(&mutex); + nb--; + printf("philosophe[%d] mange\n", i); + sleep(1); // manger + printf("philosophe[%d] a fini de manger\n", i); + sem_wait(&mutex); // libérer les fourchettes + fourch[G] = libre; + fourch[D] = libre; + sem_post(&mutex); + } else + sem_post(&mutex); + } + return NULL; +} + +int main() +{ + int i, NumPhi[N] = { 0, 1, 2, 3, 4 }; + pthread_t th[N]; + sem_init(&mutex, 0, 1); + // création des N philosophes + for (i = 0; i < N; i++) + pthread_create(&th[i], NULL, philosophe, &NumPhi[i]); + // attendre la fin des threads + for (i = 0; i < N; i++) + pthread_join(th[i], NULL); + printf("fin des threads \n"); + return 0; +}