From 5c309f2f02a0b851f54db375dffde3c01b653d63 Mon Sep 17 00:00:00 2001 From: Camille Chauvet Date: Tue, 2 May 2023 11:44:16 +0000 Subject: [PATCH] fix: sleeptime and eat time if time to die < time eat|sleep --- philo_routine.c | 8 ++++---- time.c | 28 ++++++++++++++++++++++------ time.h | 5 +++-- 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/philo_routine.c b/philo_routine.c index 3253507..25979b5 100644 --- a/philo_routine.c +++ b/philo_routine.c @@ -6,7 +6,7 @@ /* By: cchauvet forks[philo->id]); pthread_mutex_unlock(&data->forks[(philo->id + 1) % data->nb_philos]); if (check(philo, data)) @@ -89,7 +89,7 @@ bool philo_eat(t_philo *philo, t_data *data) void philo_sleep(t_data *data, t_philo *philo) { print_sleeping(philo); - usleep(data->eat_time * 1000); + usleep(get_time_sleep(philo, data) * 1000); } void *philo_routine(void *arg) @@ -100,7 +100,7 @@ void *philo_routine(void *arg) philo = arg; data = philo->data; print_thinking(philo); - usleep((philo->id % 2) * (data->eat_time) * 1000); + usleep((philo->id % 2) * (get_time_eat(philo, data)) * 1000); while (true) { if (check(philo, data)) diff --git a/time.c b/time.c index 4063275..7392b5a 100644 --- a/time.c +++ b/time.c @@ -6,7 +6,7 @@ /* By: cchauvet last_eat + data->eat_time > data->life_expectency) - return ((time - philo->last_eat + data->eat_time)); - else - return (data->eat_time); + value = (data->life_expectency - philo->last_eat - time); + if (value > data->eat_time) + value = data->eat_time; + // printf("\n%zu: time: %zu, last: %zu, eat: %zu, expectencty: %zu, value: %zu\n", philo->id + 1, time, philo->last_eat, data->eat_time, data->life_expectency, value); + return (value); } + +size_t get_time_sleep(t_philo *philo, t_data *data) +{ + size_t time; + size_t value; + + time = get_time(); + value = (data->life_expectency - (time - philo->last_eat)); + if (value > data->sleep_time) + value = data->sleep_time; + // printf("\n%zu: time: %zu, last: %zu, sleep: %zu, expectencty: %zu, value: %zu\n", philo->id + 1, time, philo->last_eat, data->sleep_time, data->life_expectency, value); + return (value); +} + diff --git a/time.h b/time.h index ec75214..d5e0dd1 100644 --- a/time.h +++ b/time.h @@ -6,7 +6,7 @@ /* By: cchauvet size_t get_time(void); -size_t get_time_perfect(t_philo *philo, t_data *data); +size_t get_time_eat(t_philo *philo, t_data *data); +size_t get_time_sleep(t_philo *philo, t_data *data); #endif