|
|
|
/* ************************************************************************** */
|
|
|
|
/* */
|
|
|
|
/* ::: :::::::: */
|
|
|
|
/* philo_launcher.c :+: :+: :+: */
|
|
|
|
/* +:+ +:+ +:+ */
|
|
|
|
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
|
|
|
|
/* +#+#+#+#+#+ +#+ */
|
|
|
|
/* Created: 2021/11/24 15:44:04 by narnaud #+# #+# */
|
|
|
|
/* Updated: 2022/05/16 18:04:42 by narnaud ### ########.fr */
|
|
|
|
/* */
|
|
|
|
/* ************************************************************************** */
|
|
|
|
|
|
|
|
#include "philosophers.h"
|
|
|
|
|
|
|
|
int waiter(t_room *room);
|
|
|
|
|
|
|
|
int main(int argc, char **argv)
|
|
|
|
{
|
|
|
|
t_room *room;
|
|
|
|
|
|
|
|
if (argc < 5 || argc > 6)
|
|
|
|
return (1);
|
|
|
|
room = init_room(argv + 1);
|
|
|
|
while (room->i >= 0)
|
|
|
|
{
|
|
|
|
pthread_mutex_lock(room->safe);
|
|
|
|
if (room->i >= room->param->philo_amount)
|
|
|
|
room->i -= 1 + (room->param->philo_amount % 2) * 2;
|
|
|
|
pthread_create(room->philos[room->i]->thd, NULL, \
|
|
|
|
philos_life, (void *)room);
|
|
|
|
pthread_detach(*room->philos[room->i]->thd);
|
|
|
|
pthread_mutex_unlock(room->safe);
|
|
|
|
usleep(CLOCK_ONE);
|
|
|
|
pthread_mutex_lock(room->safe);
|
|
|
|
if ((room->i % 2) == 0)
|
|
|
|
room->i += 2;
|
|
|
|
else if ((room->i % 2) == 1)
|
|
|
|
room->i -= 2;
|
|
|
|
pthread_mutex_unlock(room->safe);
|
|
|
|
}
|
|
|
|
while (!waiter(room))
|
|
|
|
usleep(CLOCK_TWO);
|
|
|
|
return (clean_memory(room));
|
|
|
|
}
|
|
|
|
|
|
|
|
int waiter(t_room *room)
|
|
|
|
{
|
|
|
|
t_param *param;
|
|
|
|
int i;
|
|
|
|
int starvest;
|
|
|
|
|
|
|
|
pthread_mutex_lock(room->safe);
|
|
|
|
i = 0;
|
|
|
|
param = room->param;
|
|
|
|
starvest = param->eat_amount;
|
|
|
|
while (i < param->philo_amount)
|
|
|
|
{
|
|
|
|
pthread_mutex_lock(room->philos[i]->safe);
|
|
|
|
if (room->philos[i]->eat_time + param->die_time < gettime())
|
|
|
|
{
|
|
|
|
safe_print("%ld %d died\n", room, i);
|
|
|
|
room->running = 0;
|
|
|
|
return (1);
|
|
|
|
}
|
|
|
|
if (room->philos[i]->eat_amount < starvest)
|
|
|
|
starvest = room->philos[i]->eat_amount;
|
|
|
|
pthread_mutex_unlock(room->philos[i]->safe);
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
if (starvest == param->eat_amount)
|
|
|
|
room->running = 0;
|
|
|
|
pthread_mutex_unlock(room->safe);
|
|
|
|
return (!room->running);
|
|
|
|
}
|