42_Philosopher/philo_routine.c
Camille Chauvet 291c7b40b1 finish
2023-05-16 11:25:20 +00:00

119 lines
3.2 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_routine.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/27 11:44:14 by cchauvet #+# #+# */
/* Updated: 2023/05/16 13:13:13 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include "./time.h"
#include "./philo.h"
#include "./print.h"
#include "data.h"
bool check(t_philo *philo, t_data *data)
{
bool stop;
if (get_min_meal(data) == data->nb_meals)
{
pthread_mutex_lock(&philo->stop_mutex);
philo->stop = 1;
pthread_mutex_unlock(&philo->stop_mutex);
return (1);
}
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);
}
int philo_take_forks(t_philo *philo, t_data *data)
{
pthread_mutex_lock(&data->forks[philo->id]);
print_take_a_fork(philo);
if (check(philo, data))
{
pthread_mutex_unlock(&data->forks[philo->id]);
return (1);
}
while ((philo->id + 1) % data->nb_philos == philo->id)
{
if (check(philo, data))
{
pthread_mutex_unlock(&data->forks[philo->id]);
return (1);
}
}
pthread_mutex_lock(&data->forks[(philo->id + 1) % data->nb_philos]);
print_take_a_fork(philo);
if (check(philo, data))
{
pthread_mutex_unlock(&data->forks[(philo->id + 1) % data->nb_philos]);
pthread_mutex_unlock(&data->forks[philo->id]);
return (1);
}
return (0);
}
bool philo_eat(t_philo *philo, t_data *data)
{
if (philo_take_forks(philo, data))
return (1);
philo->last_eat = get_time();
print_eating(philo);
usleep(get_time_eat(philo, data) * 1000);
pthread_mutex_unlock(&data->forks[philo->id]);
pthread_mutex_unlock(&data->forks[(philo->id + 1) % data->nb_philos]);
if (check(philo, data))
return (1);
pthread_mutex_lock(&philo->last_eat_mutex);
pthread_mutex_unlock(&philo->last_eat_mutex);
pthread_mutex_lock(&philo->nb_meal_mutex);
philo->nb_meal++;
pthread_mutex_unlock(&philo->nb_meal_mutex);
return (0);
}
void philo_sleep(t_data *data, t_philo *philo)
{
print_sleeping(philo);
usleep(get_time_sleep(philo, data) * 1000);
}
void *philo_routine(void *arg)
{
t_philo *philo;
t_data *data;
philo = arg;
data = philo->data;
print_thinking(philo);
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))
return (NULL);
print_thinking(philo);
}
return (NULL);
}