From: Lukas Jiriste Date: Thu, 3 Oct 2024 07:15:55 +0000 (+0200) Subject: Add time_to_think to increase survivability X-Git-Url: https://git.ljiriste.work/?a=commitdiff_plain;h=refs%2Fheads%2Ftrunk;p=42%2Fphilosophers.git Add time_to_think to increase survivability I thought that the program should be a tool to demonstrate the dangers in parallel computing. Hence I let the user wholly define what philosophers can do. This point of view has however failed me multiple times during evaluation... This (and a couple of conversations) led me to believe the only way to pass is to add another element - the time_to_think. When odd number of philosophers is entered and the time_to_sleep is too low, the time_to_think is set to such a value that philosophers can share the forks fairly. --- diff --git a/philo/parsing.c b/philo/parsing.c index ec9a39f..90d6c5c 100644 --- a/philo/parsing.c +++ b/philo/parsing.c @@ -15,6 +15,8 @@ #include #include +#define RESERVE 100 + int is_sane(t_settings *settings) { return (settings->philo_count > 0); @@ -33,6 +35,13 @@ int parse_input(t_settings *settings, int argc, char **argv) { return (1); } + if (settings->philo_count % 2 + && 3 * settings->time_to_eat < settings->time_to_die + && 2 * settings->time_to_eat > settings->time_to_sleep) + settings->time_to_think = 2 * settings->time_to_eat + - settings->time_to_sleep + RESERVE; + else + settings->time_to_think = 0; if (argc == 6) { if (parse_arg_uint(&settings->min_eat_num, argv[5])) diff --git a/philo/philo.c b/philo/philo.c index f0f52fc..e1fe1f0 100644 --- a/philo/philo.c +++ b/philo/philo.c @@ -15,7 +15,8 @@ static void philo_think(t_philo *philo) { - report(philo, "is thinking"); + if (!report(philo, "is thinking")) + usleep(philo->settings->time_to_think); return ; } @@ -82,13 +83,14 @@ void *be_a_philosopher(void *void_philo) { t_philo *const philo = void_philo; + report(philo, "is thinking"); if (philo->id % 2) usleep(1000); while (!end(philo->settings)) { - philo_think(philo); philo_eat(philo); philo_sleep(philo); + philo_think(philo); } return (NULL); } diff --git a/philo/philo.h b/philo/philo.h index 8eeed58..698d2b6 100644 --- a/philo/philo.h +++ b/philo/philo.h @@ -35,6 +35,7 @@ typedef struct s_settings useconds_t time_to_die; useconds_t time_to_eat; useconds_t time_to_sleep; + useconds_t time_to_think; size_t philo_count; struct timeval start; t_mutex terminal_lock;