/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* exec.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hulamy +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2022/01/26 15:30:28 by hulamy #+# #+# */ /* Updated: 2022/01/26 18:51:44 by hulamy ### ########.fr */ /* */ /* ************************************************************************** */ #include "philo.h" static void action_delay(t_philo *philo, int action_time) { struct timeval stime; int death_time; gettimeofday(&stime, NULL); death_time = philo->params->t_die - diff_time(&philo->t_last_meal, &stime); if (death_time > action_time) usleep(action_time * 1000); else if (death_time > 0) usleep(philo->params->t_die * 1000); } static int ret_err_unlock(t_philo *philo, int nbr_fork) { pthread_mutex_unlock(&philo->m_fork); if (nbr_fork == 2) pthread_mutex_unlock(&philo->next->m_fork); return (1); } static int eat(t_philo *philo) { pthread_mutex_lock(&(philo->m_fork)); if (print_message(philo, WHITE, "has taken a fork")) return (ret_err_unlock(philo, 1)); pthread_mutex_lock(&(philo->next->m_fork)); if (print_message(philo, WHITE, "has taken a fork")) return (ret_err_unlock(philo, 2)); update_time(philo); if (print_message(philo, B_YELLOW, "is eating")) return (ret_err_unlock(philo, 2)); action_delay(philo, philo->params->t_eat); philo->eat_count++; pthread_mutex_unlock(&(philo->next->m_fork)); pthread_mutex_unlock(&(philo->m_fork)); return (0); } void *philo_exec(void *arg) { t_philo *philo; philo = (t_philo *)arg; init_time(philo); if (philo->p_nbr % 2 == 0) usleep(10 * 1000); while (1) { if (eat(philo) != 0) break ; if (print_message(philo, B_BLUE, "is sleeping")) break ; action_delay(philo, philo->params->t_slp); if (print_message(philo, B_GREEN, "is thinking")) break ; } return (NULL); }