2024-07-23 18:11:44 +02:00
|
|
|
/* ************************************************************************** */
|
|
|
|
/* */
|
|
|
|
/* ::: :::::::: */
|
|
|
|
/* philo_routine.c :+: :+: :+: */
|
|
|
|
/* +:+ +:+ +:+ */
|
|
|
|
/* By: adjoly <adjoly@student.42angouleme.fr> +#+ +:+ +#+ */
|
|
|
|
/* +#+#+#+#+#+ +#+ */
|
|
|
|
/* Created: 2024/07/22 21:24:53 by adjoly #+# #+# */
|
2024-07-25 20:08:26 +02:00
|
|
|
/* Updated: 2024/07/25 20:06:20 by adjoly ### ########.fr */
|
2024-07-23 18:11:44 +02:00
|
|
|
/* */
|
|
|
|
/* ************************************************************************** */
|
|
|
|
|
|
|
|
#include "philo.h"
|
|
|
|
#include <stdio.h>
|
|
|
|
|
2024-07-25 20:08:26 +02:00
|
|
|
|
|
|
|
void take_fork(t_fork *fork, int id)
|
|
|
|
{
|
|
|
|
if (id % 2)
|
|
|
|
{
|
|
|
|
pthread_mutex_lock(&fork->left);
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
pthread_mutex_lock(fork->right);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-07-23 18:11:44 +02:00
|
|
|
void *philo_routine(void *content)
|
|
|
|
{
|
|
|
|
t_philo philo;
|
2024-07-25 16:13:23 +02:00
|
|
|
bool death;
|
|
|
|
int i = 0;
|
2024-07-23 18:11:44 +02:00
|
|
|
|
|
|
|
philo = *(t_philo *)content;
|
2024-07-25 16:13:23 +02:00
|
|
|
gettimeofday(&(philo.t0), NULL);
|
|
|
|
while (i < philo.data.meal_nbr)
|
|
|
|
{
|
2024-07-25 20:08:26 +02:00
|
|
|
log_philo(philo);
|
|
|
|
take_fork(&philo.fork, philo.id);
|
|
|
|
philo.state = FORK_TAKEN;
|
|
|
|
log_philo(philo);
|
|
|
|
take_fork(&philo.fork, philo.id + 1);
|
|
|
|
log_philo(philo);
|
2024-07-25 16:13:23 +02:00
|
|
|
philo.state = EAT;
|
|
|
|
log_philo(philo);
|
|
|
|
death = sleep_phil(philo.data.eat_time, philo.check);
|
2024-07-25 16:31:28 +02:00
|
|
|
pthread_mutex_unlock(&philo.fork.left);
|
|
|
|
pthread_mutex_unlock(philo.fork.right);
|
2024-07-25 16:13:23 +02:00
|
|
|
if (death == true)
|
|
|
|
return (NULL);
|
|
|
|
philo.state = SLEEP;
|
|
|
|
log_philo(philo);
|
|
|
|
death = sleep_phil(philo.data.sleep_time, philo.check);
|
|
|
|
if (death == true)
|
|
|
|
return (NULL);
|
|
|
|
philo.state = THINK;
|
|
|
|
log_philo(philo);
|
|
|
|
i++;
|
|
|
|
}
|
2024-07-23 18:11:44 +02:00
|
|
|
return (NULL);
|
|
|
|
}
|