#include "philo.h"

void	*philo_routine(void *arg)
{
	t_philo	*philo;

	philo = (t_philo *)arg;
	while (!philo->death && !philo->rules->death 
		&& (philo->n_eat < philo->rules->n_must_eat || philo->rules->n_must_eat == -1))
	{
		if (philo->id % 2 == 1)
		{
			pthread_mutex_lock(philo->r_fork);
			print_status(philo, "has taken a fork");
		}
		pthread_mutex_lock(philo->l_fork);
		print_status(philo, "has taken a fork");
		if (philo->id % 2 == 0)
		{
			pthread_mutex_lock(philo->r_fork);
			print_status(philo, "has taken a fork");
		}
		if (!check_alive(philo))
			break ;
		print_status(philo, "is eating");
		philo->last_meal = get_time();
		philo->n_eat++;
		usleep(philo->rules->time_to_eat * 1000);
		pthread_mutex_unlock(philo->l_fork);
		pthread_mutex_unlock(philo->r_fork);
		print_status(philo, "is sleeping");
		usleep(philo->rules->time_to_sleep * 1000);
		print_status(philo, "is thinking");
	}
	return (NULL);
}