Files
42_INT_08_philosophers/srcs/init.c
2022-01-10 15:44:30 +01:00

80 lines
1.5 KiB
C

#include "philo.h"
t_philo *init_struc_philo(t_philo *new, t_conditions *conditions, int i)
{
new->conditions = conditions;
new->philo_nbr = i + 1;
new->fork = 1;
return (new);
}
// it's just because init_chain_philo was too long
void put_prev_n_next(t_philo *new, t_philo *philo)
{
new->prev = philo;
philo->next = new;
}
t_philo *init_chain_philo(t_conditions *conditions, int n)
{
t_philo *start;
t_philo *philo;
t_philo *new;
int i;
i = 0;
while (i < n)
{
new = malloc(sizeof(t_philo) * 1);
if (new == NULL)
return (NULL);
new = init_struc_philo(new, conditions, i);
if (i == 0)
start = new;
else
put_prev_n_next(new, philo);
philo = new;
i++;
}
philo = start;
philo->prev = new;
new->next = philo;
return (philo);
}
t_conditions *init_conditions(int ac, char **av)
{
t_conditions *conditions;
if (ac == 5 || ac == 6)
{
conditions = malloc(sizeof(t_conditions));
conditions->n_phi = ft_atoi(av[1]);
conditions->t_die = ft_atoi(av[2]);
conditions->t_eat = ft_atoi(av[3]);
conditions->t_slp = ft_atoi(av[4]);
if (ac == 6)
conditions->n_eat = ft_atoi(av[5]);
}
else
return (NULL);
return (conditions);
}
t_philo *init(int ac, char **av, pthread_t **id)
{
t_philo *philo;
t_conditions *conditions;
conditions = init_conditions(ac, av);
if (conditions == NULL)
return (NULL);
*id = malloc(sizeof(int) * conditions->n_phi);
if (*id == NULL)
return (NULL);
philo = init_chain_philo(conditions, conditions->n_phi);
if (philo == NULL)
return (NULL);
return (philo);
}