126 lines
2.9 KiB
C
126 lines
2.9 KiB
C
/* ************************************************************************** */
|
|
/* */
|
|
/* ::: :::::::: */
|
|
/* manage_threads.c :+: :+: :+: */
|
|
/* +:+ +:+ +:+ */
|
|
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
|
|
/* +#+#+#+#+#+ +#+ */
|
|
/* Created: 2023/03/29 20:44:30 by erey-bet #+# #+# */
|
|
/* Updated: 2023/04/08 19:40:03 by erey-bet ### ########.fr */
|
|
/* */
|
|
/* ************************************************************************** */
|
|
|
|
#include "philo.h"
|
|
|
|
int *init_forks(t_config *config)
|
|
{
|
|
int *forks;
|
|
int i;
|
|
|
|
forks = ft_calloc(sizeof(int), config->nbr_philo);
|
|
if (!forks)
|
|
return (NULL);
|
|
i = 0;
|
|
while (i < config->nbr_philo)
|
|
forks[i++] = 1;
|
|
return (forks);
|
|
}
|
|
|
|
static t_same *create_struct_same(t_config *config)
|
|
{
|
|
t_same *same;
|
|
|
|
same = ft_calloc(sizeof(t_same), 1);
|
|
if (!same)
|
|
return (NULL);
|
|
same->forks = init_forks(config);
|
|
if (!same->forks)
|
|
{
|
|
free(same);
|
|
return (NULL);
|
|
}
|
|
same->mutex = ft_calloc(sizeof(pthread_mutex_t), config->nbr_philo + 3);
|
|
if (!same->mutex)
|
|
{
|
|
free(same->forks);
|
|
free(same);
|
|
return (NULL);
|
|
}
|
|
if (init_mutex(same->mutex, config->nbr_philo + 3))
|
|
{
|
|
free(same->forks);
|
|
free(same->mutex);
|
|
free(same);
|
|
return (NULL);
|
|
}
|
|
same->config = config;
|
|
same->death = 0;
|
|
same->all_eat = 0;
|
|
same->time = get_utime();
|
|
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;
|
|
|
|
if (!same)
|
|
{
|
|
if (only)
|
|
free(only);
|
|
return (NULL);
|
|
}
|
|
if (!only)
|
|
{
|
|
free(same);
|
|
return (NULL);
|
|
}
|
|
philo = ft_calloc(sizeof(t_philo), 1);
|
|
if (!philo)
|
|
return (NULL);
|
|
philo->same = same;
|
|
philo->only = only;
|
|
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 (free_all(thds, NULL, NULL));
|
|
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 (free_all(thds, same, philo));
|
|
}
|
|
philo[i] = NULL;
|
|
while (--i > -1)
|
|
pthread_join(thds[i], NULL);
|
|
free_all(thds, same, philo);
|
|
return (0);
|
|
}
|