fix: data race

This commit is contained in:
Camille Chauvet 2023-05-24 16:19:21 +02:00
parent 550851a5c8
commit 1b3c96b38d

View File

@ -6,7 +6,7 @@
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */ /* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/27 11:44:14 by cchauvet #+# #+# */ /* Created: 2023/04/27 11:44:14 by cchauvet #+# #+# */
/* Updated: 2023/05/24 13:38:11 by cchauvet ### ########.fr */ /* Updated: 2023/05/24 14:03:42 by cchauvet ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -16,6 +16,13 @@
#include "./print.h" #include "./print.h"
#include "data.h" #include "data.h"
void philo_stop(t_philo *philo)
{
pthread_mutex_lock(&philo->stop_mutex);
philo->stop = 1;
pthread_mutex_unlock(&philo->stop_mutex);
}
bool check(t_philo *philo, t_data *data) bool check(t_philo *philo, t_data *data)
{ {
bool stop; bool stop;
@ -30,12 +37,6 @@ bool check(t_philo *philo, t_data *data)
pthread_mutex_lock(&data->stop_mutex); pthread_mutex_lock(&data->stop_mutex);
stop = data->stop; stop = data->stop;
pthread_mutex_unlock(&data->stop_mutex); 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); return (stop);
} }
@ -86,10 +87,11 @@ bool philo_eat(t_philo *philo, t_data *data)
return (0); return (0);
} }
void philo_sleep(t_data *data, t_philo *philo) int philo_sleep(t_data *data, t_philo *philo)
{ {
print_sleeping(philo); print_sleeping(philo);
usleep(get_time_sleep(philo, data) * 1000); usleep(get_time_sleep(philo, data) * 1000);
return (0);
} }
void *philo_routine(void *arg) void *philo_routine(void *arg)
@ -103,15 +105,15 @@ void *philo_routine(void *arg)
usleep((philo->id % 2) * (get_time_eat(philo, data)) * 1000); usleep((philo->id % 2) * (get_time_eat(philo, data)) * 1000);
while (true) while (true)
{ {
if (check(philo, data)) if (check(philo, data)
return (NULL); || philo_eat(philo, data)
if (philo_eat(philo, data)) || check(philo, data)
return (NULL); || philo_sleep(data, philo)
if (check(philo, data)) || check(philo, data))
return (NULL); {
philo_sleep(data, philo); philo_stop(philo);
if (check(philo, data))
return (NULL); return (NULL);
}
print_thinking(philo); print_thinking(philo);
} }
return (NULL); return (NULL);