philosopher/philo/threads.c
Etienne Rey-bethbeder e88ec90f41 Add
2023-03-13 18:34:33 +01:00

65 lines
1.9 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* threads.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: erey-bet <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/03/08 20:08:33 by erey-bet #+# #+# */
/* Updated: 2023/03/13 18:33:50 by erey-bet ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
#include <pthread.h>
void *philosopher(t_philo *philo)
{
pthread_mutex_lock(&philo->mutex);
write(1, "Hey i'm ", 8);
ft_putnbr_fd(*philo->id, 1);
write(1, "\n", 1);
pthread_mutex_unlock(&philo->mutex);
return (NULL);
}
int manage_threads(t_config *config)
{
pthread_t *threads;
pthread_mutex_t mutex_first_fork;
pthread_mutex_t mutex_second_fork;
pthread_mutex_t mutex_dead;
t_philo *philo;
int i;
threads = malloc(config->nbr_philo * sizeof(pthread_t));
if (threads == NULL)
return (1);
pthread_mutex_init(&mutex, NULL);
philo = ft_calloc(sizeof(t_philo), 1);
if (!philo)
return (1);
philo->conf = *config;
philo->mutex = mutex;
i = -1;
while (++i < config->nbr_philo)
{
philo->id = &i;
if (pthread_create(&threads[i], NULL, (void *)&philosopher, philo) != 0)
{
write(2, "Error thread creation\n", 21);
return (1);
}
}
while (--i > -1)
{
if (pthread_join(threads[i], NULL) != 0)
{
write(2, "Error thread finish\n", 20);
return (1);
}
}
pthread_mutex_destroy(&mutex);
return (0);
}