42 school project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.0 KiB

3 years ago
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_life.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/26 07:43:48 by narnaud #+# #+# */
/* Updated: 2022/05/20 08:35:19 by narnaud ### ########.fr */
3 years ago
/* */
/* ************************************************************************** */
#include "philo.h"
static int eat(t_room *room, t_philo *philo)
{
pthread_mutex_lock(philo->fork);
if (!safe_print(philo, "%d %d has taken a fork\n")
|| !philo->fork_r)
3 years ago
return (1);
pthread_mutex_lock(philo->fork_r);
safe_print(philo, "%d %d has taken a fork\n");
if (!safe_print(philo, "%d %d is eating\n"))
return (2);
pthread_mutex_lock(philo->lock);
philo->eat_time = room_clock();
pthread_mutex_unlock(philo->lock);
if (!safe_wait(room, room_clock(), EAT_DURATION))
return (2);
pthread_mutex_unlock(philo->fork);
pthread_mutex_unlock(philo->fork_r);
pthread_mutex_lock(philo->lock);
philo->eat_amount++;
pthread_mutex_unlock(philo->lock);
return (0);
}
void *philos_life(void *ph)
{
t_philo *philo;
int stop;
philo = (t_philo *)ph;
while (1)
{
stop = eat(philo->room, philo);
if (stop)
break ;
if (!safe_print(philo, "%d %d is sleeping\n"))
break ;
if (!safe_wait(philo->room, room_clock(), SLEEP_DURATION))
break ;
if (!safe_print(philo, "%d %d is thinking\n"))
break ;
}
if (stop > 0)
3 years ago
pthread_mutex_unlock(philo->fork);
if (stop > 1)
3 years ago
pthread_mutex_unlock(philo->fork_r);
return (NULL);
}