void choose_action2(t_data *data, int prior1, int prior2) { if (prior1 == 1 && prior2 == data->i) reflechi_other(data); if (prior1 == 1) reflechi_current(data); if (prior1 == 2) mange(data); if (prior1 == 0) repos(data); }
void* philosophe ( void* arg ) { int *id=(int *) arg; int left = *id; int right = (left + 1) % PHILOSOPHES; while(true) { printf("Philosophe [%d] pense\n",*id); sem_wait(&baguette[left]); printf("Philosophe [%d] possède baguette gauche [%d]\n",*id,left); sem_wait(&baguette[right]); printf("Philosophe [%d] possède baguette droite [%d]\n",*id,right); mange(*id); sem_post(&baguette[left]); printf("Philosophe [%d] a libéré baguette gauche [%d]\n",*id,left); sem_post(&baguette[right]); printf("Philosophe [%d] a libéré baguette droite [%d]\n",*id,right); } return (NULL); }
int main(int argc, char * argv[]) { srand(time(NULL)); if (argc != 1) { perror("Le programme ne prend pas d'argument !"); } key_t clef; int id_sem, status = 1, id_shm; pid_t pid = 0; char * shared; clef = ftok(argv[0], 'A'); id_sem = semget(clef, 6, IPC_CREAT | 0600); semctl(id_sem, 0, SETVAL, 1); semctl(id_sem, 1, SETVAL, 1); semctl(id_sem, 2, SETVAL, 1); semctl(id_sem, 3, SETVAL, 1); semctl(id_sem, 4, SETVAL, 1); semctl(id_sem, 5, SETVAL, 1); id_shm = shmget(clef, 5, IPC_CREAT | 0600); shared = shmat(id_shm, NULL, 0); strcpy(shared, "PPPPP"); pid = fork(); if (pid == -1) { perror("fork()"); } else if (pid == 0) { pid = fork(); if (pid == -1) { perror("fork()"); } else if (pid == 0) { pid = fork(); if (pid == -1) { perror("fork()"); } else if (pid == 0) { pid = fork(); if (pid == -1) { perror("fork()"); } else if (pid == 0) { srand(time(NULL)); shared = shmat(id_shm, NULL, 0); while (1) { pense(shared, id_sem, 4); demande(shared, id_sem, 4); mange(shared, id_sem, 4); } exit(status); } else { srand(time(NULL)); shared = shmat(id_shm, NULL, 0); while (1) { pense(shared, id_sem, 3); demande(shared, id_sem, 3); mange(shared, id_sem, 3); } pid = waitpid(pid, &status, WIFEXITED(1)); exit(status); } } else { srand(time(NULL)); shared = shmat(id_shm, NULL, 0); while (1) { pense(shared, id_sem, 2); demande(shared, id_sem, 2); mange(shared, id_sem, 2); } pid = waitpid(pid, &status, WIFEXITED(1)); exit(status); } } else { srand(time(NULL)); shared = shmat(id_shm, NULL, 0); while (1) { pense(shared, id_sem, 1); demande(shared, id_sem, 1); mange(shared, id_sem, 1); } pid = waitpid(pid, &status, WIFEXITED(1)); exit(status); } } else { while (1) { pense(shared, id_sem, 0); demande(shared, id_sem, 0); mange(shared, id_sem, 0); } pid = waitpid(pid, &status, WIFEXITED(1)); exit(status); } return 0; }