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.
61 lines
2.0 KiB
61 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/19 00:48:41 by narnaud@stude ### ########.fr */
|
||
|
/* */
|
||
|
/* ************************************************************************** */
|
||
|
|
||
|
#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"))
|
||
|
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--)
|
||
|
pthread_mutex_unlock(philo->fork);
|
||
|
if (stop--)
|
||
|
pthread_mutex_unlock(philo->fork_r);
|
||
|
return (NULL);
|
||
|
}
|