diff options
Diffstat (limited to 'src/utils_routine.c')
| -rw-r--r-- | src/utils_routine.c | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/src/utils_routine.c b/src/utils_routine.c new file mode 100644 index 0000000..37e3f3d --- /dev/null +++ b/src/utils_routine.c @@ -0,0 +1,81 @@ +#include "codexion.h" +# include <stdio.h> // for printf() +# include <unistd.h> // for usleep() + +void eat(t_philo *philo) +{ + t_sim *sim; + + (void)pthread_mutex_lock(&philo->mutex_sim); + sim = philo->sim; + (void)pthread_mutex_unlock(&philo->mutex_sim); + (void)pthread_mutex_lock(&philo->mutex_beginning_last_eat_time); + philo->beginning_last_eat_time = get_rel_time(sim); + (void)pthread_mutex_unlock(&philo->mutex_beginning_last_eat_time); + print_log(philo, "is eating", 0); + usleep(philo->sim->time_to_eat * 1000); + (void)pthread_mutex_lock(&philo->mutex_number_of_eats_done); + philo->number_of_eats_done++; + (void)pthread_mutex_unlock(&philo->mutex_number_of_eats_done); +} + +void reflect_and_think(t_philo *philo) +{ + print_log(philo, "is reflecting", 0); + usleep(philo->sim->time_to_reflect * 1000); + print_log(philo, "is thinking", 0); + usleep(philo->sim->time_to_think * 1000); +} + +int wait_for_fork(t_philo *philo, t_fork *fork) +{ + int cooldown; + int wait; + int last_released; + t_sim *sim; + + (void)pthread_mutex_lock(&philo->mutex_sim); + sim = philo->sim; + (void)pthread_mutex_unlock(&philo->mutex_sim); + (void)pthread_mutex_lock(&philo->sim->mutex_cooldown); + cooldown = philo->sim->fork_cooldown; + (void)pthread_mutex_unlock(&philo->sim->mutex_cooldown); + (void)pthread_mutex_lock(&fork->mutex_last_released); + last_released = fork->last_released; + (void)pthread_mutex_unlock(&fork->mutex_last_released); + wait = cooldown - (get_rel_time(sim) - last_released); + return (wait); +} + +void wait_for_longest_cooldown(t_philo *philo, t_fork *f1, t_fork *f2) +{ + int w1; + int w2; + int wait; + + wait = 0; + if (get_id(philo) % 2 != 0 && philo->number_of_eats_done < 1) + usleep(50); + w1 = wait_for_fork(philo, f1); + w2 = wait_for_fork(philo, f2); + if (w1 >= w2 && w1 > 0) + wait = w1; + else if (w2 >= w1 && w2 > 0) + wait = w2; + usleep(wait * 1000); +} + +void update_last_released(t_sim *sim, t_fork *f1, t_fork *f2) +{ + int time_to_eat; + + (void)pthread_mutex_lock(&sim->mutex_time_to_eat); + time_to_eat = sim->time_to_eat; + (void)pthread_mutex_unlock(&sim->mutex_time_to_eat); + (void)pthread_mutex_lock(&f1->mutex_last_released); + f1->last_released = get_rel_time(sim) + time_to_eat; + (void)pthread_mutex_unlock(&f1->mutex_last_released); + (void)pthread_mutex_lock(&f2->mutex_last_released); + f2->last_released = get_rel_time(sim) + time_to_eat; + (void)pthread_mutex_unlock(&f2->mutex_last_released); +} |
