1
0
This repository has been archived on 2024-10-25. You can view files and clone it, but cannot push or open issues or pull requests.

49 lines
1.7 KiB
C
Raw Normal View History

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* eat.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: adjoly <adjoly@student.42angouleme.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/08 17:29:51 by adjoly #+# #+# */
/* Updated: 2024/08/12 21:04:57 by adjoly ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
2024-08-12 20:52:02 +02:00
void take_fork(t_fork *fork, int id)
{
if (id % 2)
pthread_mutex_lock(&fork->left);
else if (!(id % 2))
pthread_mutex_lock(fork->right);
}
bool philo_eat(t_philo *philo)
{
philo->state = FORK_TAKEN;
2024-08-12 20:52:02 +02:00
if (get_death(philo, RETURN))
return (true);
take_fork(&philo->fork, philo->id);
log_philo(philo);
if (&(philo->fork.left) == philo->fork.right)
2024-08-12 20:52:02 +02:00
return (print_death(philo));
if (get_death(philo, RETURN))
return (true);
take_fork(&philo->fork, philo->id + 1);
log_philo(philo);
philo->state = EAT;
log_philo(philo);
pthread_mutex_lock(philo->check);
2024-08-12 20:52:02 +02:00
gettimeofday(&philo->eat, NULL);
pthread_mutex_unlock(philo->check);
if (sleep_phil(philo) == true)
return (true);
pthread_mutex_unlock(&philo->fork.left);
pthread_mutex_unlock(philo->fork.right);
2024-08-12 20:52:02 +02:00
if (philo->data.no_meal == false && philo->meal_left > 0)
philo->meal_left--;
return (false);
}