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.
 
 

87 lines
2.5 KiB

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: narnaud@student.42nice.fr <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/19 00:36:57 by narnaud@stude #+# #+# */
/* Updated: 2022/05/19 20:01:36 by narnaud@stude ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
static int waiter(t_room *room, t_philo *philo);
static int clean_memory(t_room *room, t_philo *philos);
int main(int argc, char **argv)
{
t_room *room;
t_philo *philos;
if (argc < 5 || argc > 6)
return (EXIT_FAILURE);
room = create_room(argv + 1);
philos = create_philos(room);
invit_philos(philos);
while (waiter(room, philos))
usleep(1000);
pthread_mutex_lock(room->lock);
room->running = 0;
pthread_mutex_unlock(room->lock);
sleep(1);
return (clean_memory(room, philos));
}
static int waiter(t_room *room, t_philo *philo)
{
int starvest;
int ret;
ret = 1;
usleep(1000);
pthread_mutex_lock(room->lock);
starvest = room->param[MEALS_AMOUNT];
while (ret && philo->id >= 0)
{
pthread_mutex_lock(philo->lock);
if ((philo->eat_time + room->param[DIE_TIME]) < room_clock())
{
printf("%d %d died\n", room_clock(), philo->id);
ret = 0;
}
if (philo->eat_amount < starvest)
starvest = philo->eat_amount;
pthread_mutex_unlock(philo->lock);
philo++;
}
pthread_mutex_unlock(room->lock);
if (starvest == room->param[MEALS_AMOUNT])
ret = 0;
return (ret);
}
static int clean_memory(t_room *room, t_philo *philos)
{
static int i = 0;
while (i < room->param[PHILO_AMOUNT])
{
pthread_mutex_lock(philos[i].lock);
pthread_mutex_unlock(philos[i].lock);
pthread_mutex_destroy(philos[i].lock);
pthread_mutex_lock(philos[i].fork);
pthread_mutex_unlock(philos[i].fork);
pthread_mutex_destroy(philos[i].fork);
free(philos[i].lock);
free(philos[i].thd);
i++;
}
pthread_mutex_destroy(room->lock);
free(room->lock);
free(room->forks);
free(philos);
free(room);
return (0);
}