/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* philo_life.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: narnaud +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/26 07:43:48 by narnaud #+# #+# */ /* Updated: 2022/05/19 01:23:29 by narnaud ### ########.fr */ /* */ /* ************************************************************************** */ #include "philo.h" static int eat(t_room *room, t_philo *philo) { pthread_mutex_lock(philo->fork); if (!safe_print(philo, "%d %d has taken a fork\n")) return (1); pthread_mutex_lock(philo->fork_r); safe_print(philo, "%d %d has taken a fork\n"); if (!safe_print(philo, "%d %d is eating\n")) return (2); pthread_mutex_lock(philo->lock); philo->eat_time = room_clock(); pthread_mutex_unlock(philo->lock); if (!safe_wait(room, room_clock(), EAT_DURATION)) return (2); pthread_mutex_unlock(philo->fork); pthread_mutex_unlock(philo->fork_r); pthread_mutex_lock(philo->lock); philo->eat_amount++; pthread_mutex_unlock(philo->lock); return (0); } void *philos_life(void *ph) { t_philo *philo; int stop; philo = (t_philo *)ph; while (1) { stop = eat(philo->room, philo); if (stop) break ; if (!safe_print(philo, "%d %d is sleeping\n")) break ; if (!safe_wait(philo->room, room_clock(), SLEEP_DURATION)) break ; if (!safe_print(philo, "%d %d is thinking\n")) break ; } if (stop > 0) pthread_mutex_unlock(philo->fork); if (stop > 1) pthread_mutex_unlock(philo->fork_r); return (NULL); }