/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* routine_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lfirmin +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/11/22 14:47:26 by lfirmin #+# #+# */ /* Updated: 2025/03/17 03:59:51 by lfirmin ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/philo.h" int eating_1_philo(t_philo *philo) { pthread_mutex_lock(&philo->data->forks[philo->l_fork]); print_message(philo, "has taken a fork"); safe_sleep(philo, philo->data->t_die * 1000); pthread_mutex_unlock(&philo->data->forks[philo->l_fork]); return (1); } int safe_sleep(t_philo *philo, long time) { long long start_t; long long target_time; long sleep_interval; start_t = get_time(); target_time = start_t + (time / 1000); if (philo->data->nb_philo > 150) sleep_interval = 400; else if (philo->data->nb_philo > 100) sleep_interval = 300; else if (philo->data->nb_philo > 50) sleep_interval = 200; else sleep_interval = 100; while (get_time() < target_time) { if (check_if_dead(philo)) return (1); usleep(sleep_interval); } return (0); } int take_fork_2(t_philo *philo) { pthread_mutex_lock(&philo->data->forks[philo->r_fork]); if (check_if_dead(philo)) return (pthread_mutex_unlock(&philo->data->forks[philo->r_fork]), 1); if (print_message(philo, "has taken a fork")) return (pthread_mutex_unlock(&philo->data->forks[philo->r_fork]), 1); pthread_mutex_lock(&philo->data->forks[philo->l_fork]); if (check_if_dead(philo)) { pthread_mutex_unlock(&philo->data->forks[philo->l_fork]); pthread_mutex_unlock(&philo->data->forks[philo->r_fork]); return (1); } return (0); } int take_fork(t_philo *philo) { if (check_if_dead(philo)) return (1); if (philo->l_fork < philo->r_fork) { pthread_mutex_lock(&philo->data->forks[philo->l_fork]); if (check_if_dead(philo)) return (pthread_mutex_unlock (&philo->data->forks[philo->l_fork]), 1); if (print_message(philo, "has taken a fork")) return (pthread_mutex_unlock (&philo->data->forks[philo->l_fork]), 1); pthread_mutex_lock(&philo->data->forks[philo->r_fork]); if (check_if_dead(philo)) { pthread_mutex_unlock(&philo->data->forks[philo->r_fork]); pthread_mutex_unlock(&philo->data->forks[philo->l_fork]); return (1); } } else if (take_fork_2(philo)) return (1); return (0); }