fix: check if all threads is stopped before destroye data

This commit is contained in:
Camille Chauvet
2023-04-19 14:01:59 +00:00
parent 07a72c7f89
commit c674f68b2e
3 changed files with 37 additions and 10 deletions

26
philo.c
View File

@ -17,13 +17,19 @@ void philo_destroyer(t_philo *philo)
free(philo);
}
bool check(t_data *data)
bool check(t_philo *philo, t_data *data)
{
bool stop;
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);
}
@ -51,11 +57,12 @@ bool philo_eat(t_philo *philo, t_data *data)
right_fork = 0;
while (left_fork == 0 || right_fork == 0)
{
if (check(data))
if (check(philo, data))
return (1);
pthread_mutex_lock(&data->forks_mutex);
left_fork = data->forks[philo->id];
right_fork = data->forks[(philo->id + 1) % data->nb_philos];
if (((philo->id + 1) % data->nb_philos) != philo->id)
right_fork = data->forks[(philo->id + 1) % data->nb_philos];
if (right_fork && left_fork)
{
data->forks[philo->id] = 0;
@ -85,18 +92,20 @@ void *philo_routine(void *arg)
philo = arg;
data = philo->data;
if (philo->id % 2)
usleep(data->sleep_time * 1000);
print_thinking(philo);
usleep(philo->id * (data->life_expectency / data->nb_philos));
while (true)
{
print_thinking(philo);
if (check(data))
if (check(philo, data))
return (NULL);
if (philo_eat(philo, data))
return (NULL);
if (check(data))
if (check(philo, data))
return (NULL);
philo_sleep(data, philo);
if (check(philo, data))
return (NULL);
print_thinking(philo);
}
return (NULL);
}
@ -116,5 +125,6 @@ t_philo *philo_init(t_data *data)
pthread_mutex_init(&philo->nb_meal_mutex, NULL);
pthread_mutex_init(&philo->last_eat_mutex, NULL);
pthread_mutex_init(&philo->last_sleep_mutex, NULL);
pthread_mutex_init(&philo->stop_mutex, NULL);
return (philo);
}