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.

75 lines
2.3 KiB

3 years ago
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo_launcher.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud <narnaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/24 15:44:04 by narnaud #+# #+# */
3 years ago
/* Updated: 2022/05/16 18:04:42 by narnaud ### ########.fr */
3 years ago
/* */
/* ************************************************************************** */
#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);
3 years ago
if (room->philos[i]->eat_time + param->die_time < gettime())
3 years ago
{
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);
}