/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* philo.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: narnaud@student.42nice.fr +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/05/19 00:36:57 by narnaud@stude #+# #+# */ /* Updated: 2022/05/19 00:47:15 by narnaud@stude ### ########.fr */ /* */ /* ************************************************************************** */ #include "philo.h" static int waiter(t_room *room, t_philo *philo); static int clean_memory(t_room *room, t_philo *philos); int main(int argc, char **argv) { t_room *room; t_philo *philos; if (argc < 5 || argc > 6) return (EXIT_FAILURE); room = create_room(argv + 1); philos = create_philos(room); invit_philos(philos); while (waiter(room, philos)) usleep(1000); pthread_mutex_lock(room->lock); room->running = 0; pthread_mutex_unlock(room->lock); sleep(2); return (clean_memory(room, philos)); } static int waiter(t_room *room, t_philo *philo) { int starvest; int ret; ret = 1; pthread_mutex_lock(room->lock); starvest = room->param[MEALS_AMOUNT]; while (ret && philo->id >= 0) { pthread_mutex_lock(philo->lock); if (philo->eat_time + room->param[DIE_TIME] < room_clock()) { safe_print(philo, "%d %d died\n"); ret = 0; } if (philo->eat_amount < starvest) starvest = philo->eat_amount; pthread_mutex_unlock(philo->lock); philo++; } pthread_mutex_unlock(room->lock); if (starvest == room->param[MEALS_AMOUNT]) ret = 0; return (ret); } static int clean_memory(t_room *room, t_philo *philos) { static int i = 0; pthread_mutex_lock(room->lock); while (i < room->param[PHILO_AMOUNT]) { pthread_mutex_lock(philos[i].lock); pthread_mutex_unlock(philos[i].lock); pthread_mutex_destroy(philos[i].lock); pthread_mutex_lock(philos[i].fork); pthread_mutex_unlock(philos[i].fork); pthread_mutex_destroy(philos[i].fork); free(philos[i].lock); free(philos[i].thd); i++; } pthread_mutex_unlock(room->lock); pthread_mutex_destroy(room->lock); free(room->lock); free(room->forks); free(philos); free(room); return (0); }