/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* philo.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: narnaud +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/05/16 14:03:42 by narnaud #+# #+# */ /* Updated: 2022/05/16 14:03:47 by narnaud ### ########.fr */ /* */ /* ************************************************************************** */ #include "philosophers.h" void *check_halt(void * p) { size_t time; t_philo *philo; philo = p; while (1) { usleep(1000); time = gettime(); philo->table->time = time; if (time - philo->last_meal_time > philo->table->time_to_die) { printf("%lu %d died\n", time, philo->id); exit(EXIT_SUCCESS); } } } void philo_life(t_philo *philo) { t_table *table; table = philo->table; while (1) { sem_wait(table->sptr); printf("%lu %d has taken a fork\n", table->time, philo->id); sem_wait(table->sptr); printf("%lu %d has taken a fork\n", table->time, philo->id); philo->last_meal_time = table->time; printf("%lu %d is eating\n", table->time, philo->id); usleep(table->eating_time * 1000); sem_post(table->sptr); sem_post(table->sptr); printf("%lu %d is sleeping\n", table->time, philo->id); usleep(table->sleeping_time * 1000); printf("%lu %d is thinking\n", table->time, philo->id); } } void init_philos(t_table *table) { size_t i; pthread_t checks; table->pid = malloc(sizeof(pid_t) * table->nb_of_philos); memset(table->pid, 0, sizeof(pid_t) * table->nb_of_philos); i = 0; while (i < table->nb_of_philos) { table->pid[i] = fork(); table->philos[i].table = table; table->philos[i].id = i; if (!table->pid[i]) { pthread_create(&checks, NULL, check_halt, table->philos + i); philo_life(table->philos + i); } usleep(500); i++; } } int main(int argc, char **argv) { static t_table *table; static size_t i = 0; int status; sem_unlink("/chopsticks"); sem_unlink("/death"); if (argc < 5 || argc > 6) return (1); table = parsing(argv + 1); table->sptr = sem_open("/chopsticks", O_CREAT, 0664, table->nb_of_philos); table->death = sem_open("/death", O_CREAT, 0664, 1); init_philos(table); waitpid(-1, &status, 0); while (i < table->nb_of_philos) { kill(table->pid[i], SIGINT); i++; } sem_unlink("/chopsticks"); sem_unlink("/deaths"); return(0); }