Files
42_INT_08_philosophers/srcs/exec.c
2022-01-21 18:32:37 +01:00

58 lines
1.2 KiB
C

#include "philo.h"
// TODO : compare time with time before dying
void go_sleep(t_philo *philo, int time)
{
(void)philo;
usleep(time * 1000);
}
int ret_unlock(t_mtx mutex, int ret)
{
pthread_mutex_unlock(&mutex);
return (ret);
}
int take_forks(t_philo *philo)
{
pthread_mutex_lock(&(philo->m_fork));
if (philo->death)
return (ret_unlock(philo->m_fork, 1));
print_message(philo, "has taken a fork");
pthread_mutex_lock(&(philo->next->m_fork));
if (philo->death)
return (ret_unlock(philo->next->m_fork, 1));
print_message(philo, "has taken a fork");
print_message(philo, "is eating");
go_sleep(philo, philo->params->t_eat);
pthread_mutex_unlock(&(philo->next->m_fork));
pthread_mutex_unlock(&(philo->m_fork));
return (0);
}
// int n_phi; // number_of_philosophers
// int t_die; // time_to_die
// int t_eat; // time_to_eat
// int t_slp; // time_to_sleep
// int n_eat; // [number_of_times_each_philosopher_must_eat]
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 (take_forks(philo) != 0)
break ;
print_message(philo, "is sleeping");
go_sleep(philo, philo->params->t_slp);
print_message(philo, "is thinking");
}
return (NULL);
}