From 83df2b3a49bd3f627ae304bb1529e27d9b2d988c Mon Sep 17 00:00:00 2001 From: Charles Cabergs Date: Fri, 1 Jan 2021 13:58:10 +0100 Subject: Fixing philo_one segfault because not checking correctly if finished --- philo_one/src/routine.c | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) (limited to 'philo_one/src/routine.c') diff --git a/philo_one/src/routine.c b/philo_one/src/routine.c index 280f9d6..e9775cc 100644 --- a/philo_one/src/routine.c +++ b/philo_one/src/routine.c @@ -6,32 +6,40 @@ /* By: cacharle +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/10 01:11:27 by cacharle #+# #+# */ -/* Updated: 2020/12/30 13:44:25 by charles ### ########.fr */ +/* Updated: 2021/01/01 13:57:11 by charles ### ########.fr */ /* */ /* ************************************************************************** */ #include "philo_one.h" -void *routine_philo(t_philo *arg) +inline bool philo_finished(t_philo_conf *conf) { - pthread_t thread_death; - long int eat_counter; + return (!conf->all_alive || + (conf->meal_num != -1 && + conf->meal_num_finished_counter == conf->philo_num)); +} + +void *routine_philo(t_philo *arg) +{ + pthread_t thread_death; + long int eat_counter; - if (!arg->conf->all_alive) + if (philo_finished(arg->conf)) return (NULL); arg->time_last_eat = h_time_now(); if (pthread_create(&thread_death, NULL, (t_routine)routine_death, arg) != 0) return (NULL); event_think(arg); eat_counter = 0; - while (arg->conf->all_alive) + while (!philo_finished(arg->conf)) { event_take_fork(arg, arg->fork_left); event_take_fork(arg, arg->fork_right); arg->time_last_eat = h_time_now(); event_eat(arg); eat_counter++; - if (arg->conf->meal_num != -1 && eat_counter == arg->conf->meal_num) + if (!philo_finished(arg->conf) && arg->conf->meal_num != -1 && + eat_counter == arg->conf->meal_num) { pthread_mutex_lock(&arg->conf->mutex_meal_num_finished_counter); arg->conf->meal_num_finished_counter++; @@ -44,19 +52,17 @@ void *routine_philo(t_philo *arg) return (NULL); } -void *routine_death(t_philo *arg) +void *routine_death(t_philo *arg) { - t_time current; + t_time current; current = h_time_now(); - while (arg->conf->all_alive && + while (!philo_finished(arg->conf) && current - arg->time_last_eat < arg->conf->timeout_death) { current = h_time_now(); usleep(200); } - if (!arg->conf->all_alive) - return (NULL); event_die(arg); return (NULL); } -- cgit