Files
42_INT_08_philosophers/srcs/exec.c
2022-01-22 12:41:30 +01:00

61 lines
1.4 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_1, t_mtx *mutex_2, int ret)
{
if (mutex_1)
pthread_mutex_unlock(mutex_1);
if (mutex_2)
pthread_mutex_unlock(mutex_2);
return (ret);
}
int take_forks(t_philo *philo)
{
pthread_mutex_lock(&(philo->m_fork));
if (philo->params->dead != 0)
return (ret_unlock(&(philo->m_fork), NULL, 1));
print_message(philo, "has taken a fork");
pthread_mutex_lock(&(philo->next->m_fork));
if (philo->params->dead != 0)
return (ret_unlock(&(philo->m_fork), &(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);
}