philosopher/mandatory/manage_threads.c
Etienne Rey-bethbeder ffb68409b1 Finito philo
2023-03-31 18:23:57 +02:00

94 lines
2.5 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* manage_threads.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/29 20:44:30 by erey-bet #+# #+# */
/* Updated: 2023/03/31 17:52:22 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
static t_same *create_struct_same(t_config *config)
{
t_same *same;
same = ft_calloc(sizeof(t_same), 1);
if (!same)
return (NULL);
same->mutex = ft_calloc(sizeof(pthread_mutex_t), config->nbr_philo + 2);
if (!same->mutex)
return (NULL);
init_mutex(same->mutex, config->nbr_philo + 2);
same->config = config;
same->death = ft_calloc(sizeof(int), 1);
if (!same->death)
return (NULL);
*same->death = 0;
same->all_eat = ft_calloc(sizeof(int), 1);
if (!same->all_eat)
return (NULL);
*same->all_eat = 0;
return (same);
}
static t_only *create_struct_only(int id)
{
t_only *only;
only = ft_calloc(sizeof(t_only), 1);
if (!only)
return (NULL);
only->id = id;
only->eat = 0;
return (only);
}
static t_philo *init_philo(t_same *same, t_only *only)
{
t_philo *philo;
philo = ft_calloc(sizeof(t_philo), 1);
if (!philo)
return (NULL);
philo->same = same;
if (!philo->same)
return (NULL);
philo->only = only;
if (!philo->only)
return (NULL);
return (philo);
}
int manage_threads(t_config *config)
{
pthread_t *thds;
t_philo **philo;
t_same *same;
int i;
thds = ft_calloc(config->nbr_philo, sizeof(pthread_t));
if (thds == NULL)
return (1);
philo = ft_calloc(config->nbr_philo + 1, sizeof(t_philo *));
if (philo == NULL)
return (1);
same = create_struct_same(config);
i = -1;
while (++i < config->nbr_philo)
{
philo[i] = init_philo(same, create_struct_only(i));
if (!philo[i] || pthread_create(&thds[i], NULL,
(void *)&philosopher, philo[i]) != 0)
return (1);
}
philo[i] = NULL;
while (--i > -1)
pthread_join(thds[i], NULL);
free_all(thds, same, philo);
return (0);
}