From: Lukas Jiriste Date: Tue, 19 Mar 2024 11:33:16 +0000 (+0100) Subject: Add the number_of_times_each_philosopher_must_eat X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=d9608c96d98f7fad7a2c2338c6e3be2136521054;p=42%2Fphilosophers_old.git Add the number_of_times_each_philosopher_must_eat This option required minor code changes, because I tried to prepare for this in advance but I had an incorrect understanding of the option. --- diff --git a/philo/main.c b/philo/main.c index 800b8f9..0d2d0db 100644 --- a/philo/main.c +++ b/philo/main.c @@ -6,7 +6,7 @@ /* By: ljiriste +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/03/05 12:49:40 by ljiriste #+# #+# */ -/* Updated: 2024/03/19 11:31:32 by ljiriste ### ########.fr */ +/* Updated: 2024/03/19 11:55:01 by ljiriste ### ########.fr */ /* */ /* ************************************************************************** */ @@ -74,7 +74,7 @@ void philo_think(t_settings *set, size_t id) return ; } -int philo_eat(t_philo *philo) +void philo_eat(t_philo *philo) { pthread_mutex_lock(philo->forks[0]); thread_print(philo->settings, philo->id, "has taken a fork"); @@ -83,9 +83,10 @@ int philo_eat(t_philo *philo) thread_print(philo->settings, philo->id, "is eating"); philo->last_eaten = cur_time_sus(); usleep(philo->settings->time_to_eat); + ++philo->times_eaten; pthread_mutex_unlock(philo->forks[0]); pthread_mutex_unlock(philo->forks[1]); - return (0); + return ; } void *be_a_philosopher(void *inp) @@ -97,11 +98,7 @@ void *be_a_philosopher(void *inp) while (!philo->settings->end) { philo_think(philo->settings, philo->id); - if (philo_eat(philo) == 1) - break ; - ++philo->times_eaten; - if (philo->times_eaten == philo->settings->min_eats_num) - return (NULL); + philo_eat(philo); philo_sleep(philo->settings, philo->id); } return (NULL); @@ -306,14 +303,16 @@ void check_death(t_philo *philos, t_settings *set) suseconds_t oldest; suseconds_t now; size_t i; + int all_full; while (1) { i = 0; now = cur_time_sus(); + all_full = set->min_eats_num > 0; + oldest = philos[0].last_eaten; while (i < set->philo_count) { - oldest = philos[0].last_eaten; if((now - philos[i].last_eaten) > set->time_to_die) { pthread_mutex_lock(&set->terminal); @@ -324,8 +323,17 @@ void check_death(t_philo *philos, t_settings *set) } if (oldest > philos[i].last_eaten) oldest = philos[i].last_eaten; + all_full = (all_full && (philos[i].times_eaten >= set->min_eats_num)); ++i; } + if (all_full) + { + pthread_mutex_lock(&set->terminal); + printf("%li All philosophers are well fed\n", (cur_time_sus() - set->program_start) / 1000); + set->end = 1; + pthread_mutex_unlock(&set->terminal); + return ; + } now = cur_time_sus(); //usleep(now - oldest); }