From 1b3c96b38d7dc10faf99f08ac5f8f03fbc768d5a Mon Sep 17 00:00:00 2001 From: Camille Chauvet Date: Wed, 24 May 2023 16:19:21 +0200 Subject: [PATCH] fix: data race --- philo/philo_routine.c | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/philo/philo_routine.c b/philo/philo_routine.c index a11243c..ad413c1 100644 --- a/philo/philo_routine.c +++ b/philo/philo_routine.c @@ -6,7 +6,7 @@ /* By: cchauvet stop_mutex); + philo->stop = 1; + pthread_mutex_unlock(&philo->stop_mutex); +} + bool check(t_philo *philo, t_data *data) { bool stop; @@ -30,12 +37,6 @@ bool check(t_philo *philo, t_data *data) pthread_mutex_lock(&data->stop_mutex); stop = data->stop; pthread_mutex_unlock(&data->stop_mutex); - if (stop) - { - pthread_mutex_lock(&philo->stop_mutex); - philo->stop = 1; - pthread_mutex_unlock(&philo->stop_mutex); - } return (stop); } @@ -86,10 +87,11 @@ bool philo_eat(t_philo *philo, t_data *data) return (0); } -void philo_sleep(t_data *data, t_philo *philo) +int philo_sleep(t_data *data, t_philo *philo) { print_sleeping(philo); usleep(get_time_sleep(philo, data) * 1000); + return (0); } void *philo_routine(void *arg) @@ -103,15 +105,15 @@ void *philo_routine(void *arg) usleep((philo->id % 2) * (get_time_eat(philo, data)) * 1000); while (true) { - if (check(philo, data)) - return (NULL); - if (philo_eat(philo, data)) - return (NULL); - if (check(philo, data)) - return (NULL); - philo_sleep(data, philo); - if (check(philo, data)) + if (check(philo, data) + || philo_eat(philo, data) + || check(philo, data) + || philo_sleep(data, philo) + || check(philo, data)) + { + philo_stop(philo); return (NULL); + } print_thinking(philo); } return (NULL);