Add philosophe course code without famine, fixed.
[TD_SE.git] / philosophe-famine / philosophe.c
diff --git a/philosophe-famine/philosophe.c b/philosophe-famine/philosophe.c
new file mode 100644 (file)
index 0000000..69e1fe8
--- /dev/null
@@ -0,0 +1,78 @@
+// programme philosophe.c
+#include <stdio.h>
+#include <unistd.h>
+#include <pthread.h>
+#include <semaphore.h>
+
+#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 penser 0
+#define faim 1
+#define manger 2
+static int phiState[N] = { penser };
+
+sem_t mutex;
+sem_t semPhil[N];
+
+void test(int i)
+{
+       if (phiState[i] == faim && phiState[G] != manger
+           && phiState[D] != manger) {
+               phiState[i] = manger;
+               sem_post(&semPhil[i]);
+       }
+}
+
+void *philosophe(void *num)
+{
+       int i = *(int *)num, nb = 2;
+       while (nb) {
+               /* penser */
+               sem_wait(&mutex);
+               phiState[i] = penser;
+               sem_post(&mutex);
+               sleep(1);
+               /* essayer de manger */
+               sem_wait(&mutex);
+               phiState[i] = faim;
+               test(i);
+               sem_post(&mutex);
+               /* attendre son tour */
+               sem_wait(&semPhil[i]);
+               /* à nous de manger */
+               printf("philosophe[%d] mange\n", i);
+               sleep(1);
+               printf("philosophe[%d] a fini\n", i);
+               /* laisser manger ses voisins */
+               sem_wait(&mutex);
+               phiState[i] = penser;
+               test(G);
+               test(D);
+               sem_post(&mutex);
+               nb--;
+       }
+       return NULL;
+}
+
+int main()
+{
+       int i, NumPhi[N] = { 0, 1, 2, 3, 4 };
+       pthread_t th[N];
+       sem_init(&mutex, 0, 1);
+       for (int i = 0; i < N; i++) {
+               sem_init(&semPhil[i], 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;
+}