From 47beba686ff9d2aab63738fba7176a5235703d05 Mon Sep 17 00:00:00 2001 From: yctct Date: Sun, 13 Sep 2026 18:58:14 +0200 Subject: Add all files, first commit --- src/routine.c | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/routine.c (limited to 'src/routine.c') diff --git a/src/routine.c b/src/routine.c new file mode 100644 index 0000000..6d867cf --- /dev/null +++ b/src/routine.c @@ -0,0 +1,57 @@ +#include "codexion.h" +# include // for usleep() +# include // for printf() + +static void send_signal(t_fork *fork) +{ + (void)pthread_mutex_lock(&fork->mutex_cond); + pthread_cond_signal(&fork->cond_signal); + (void)pthread_mutex_unlock(&fork->mutex_cond); +} + +static void lock_forks(t_philo *philo, t_fork *f1, + t_fork *f2) +{ + if (get_id(philo) % 2 == 0) + { + (void)pthread_mutex_lock(&f1->mutex); + (void)pthread_mutex_lock(&f2->mutex); + } + else + { + if (philo->number_of_eats_done < 1) + usleep(50); + (void)pthread_mutex_lock(&f2->mutex); + (void)pthread_mutex_lock(&f1->mutex); + } + wait_for_longest_cooldown(philo, f1, f2); +} + +int philo_routine(t_philo *philo, t_fork *f1, + t_fork *f2) +{ + t_sim *sim; + + (void)pthread_mutex_lock(&philo->mutex_sim); + sim = philo->sim; + (void)pthread_mutex_unlock(&philo->mutex_sim); + if (check_if_philo_starved(sim)) + return (1); + if (queue_routine(philo, f1, f2) == 1) + return (1); + if (check_if_philo_starved(sim)) + return (1); + lock_forks(philo, f1, f2); + print_log(philo, "has taken a fork", 0); + print_log(philo, "has taken a fork", 0); + update_last_released(sim, f1, f2); + eat(philo); + (void)pthread_mutex_unlock(&f2->mutex); + dequeue(f2); + send_signal(f2); + (void)pthread_mutex_unlock(&f1->mutex); + dequeue(f1); + send_signal(f1); + reflect_and_think(philo); + return (0); +} -- cgit v1.2.3