Files
42_INT_08_philosophers/srcs/exec.c
2022-01-25 22:05:39 +01:00

65 lines
1.5 KiB
C

#include "philo.h"
void go_sleep(t_philo *philo, int action_time)
{
struct timeval stime;
int time_to_death;
gettimeofday(&stime, NULL);
time_to_death = diff_time(philo->t_last_meal, stime);
time_to_death = philo->params->t_die - time_to_death;
if (time_to_death > action_time)
usleep(action_time * 1000);
else if (time_to_death > 0)
usleep(philo->params->t_die * 1000);
}
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);
}
int eat(t_philo *philo)
{
pthread_mutex_lock(&(philo->m_fork));
if (print_message(philo, WHITE, "has taken a fork") == 1)
return (ret_err_unlock(philo, 1));
pthread_mutex_lock(&(philo->next->m_fork));
if (print_message(philo, WHITE, "has taken a fork") == 1)
return (ret_err_unlock(philo, 2));
update_time(philo);
if (print_message(philo, B_YELLOW, "is eating") == 1)
return (ret_err_unlock(philo, 2));
philo->eat++;
go_sleep(philo, philo->params->t_eat);
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") == 1)
break ;
go_sleep(philo, philo->params->t_slp);
if (print_message(philo, B_GREEN, "is thinking") == 1)
break ;
}
return (NULL);
}