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.
 
 

77 lines
2.4 KiB

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_launcher.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/24 15:44:04 by narnaud #+# #+# */
/* Updated: 2022/04/11 14:55:43 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);
pthread_create(&room->clock_thd, NULL, room_clock, (void *)room);
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 < room->time)
{
safe_print("%ld %d died\n", room, i);
room->running = 0;
pthread_mutex_unlock(room->philos[i]->safe);
pthread_mutex_unlock(room->safe);
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);
}