From 48118ae3ab7e2c6366558c259812e78bd5633357 Mon Sep 17 00:00:00 2001 From: hugogogo Date: Sun, 9 Jan 2022 11:10:04 +0100 Subject: [PATCH] resolved unexpected additionnal call to the chained list --- headers/philo_proto.h | 2 +- srcs/init.c | 4 ++-- srcs/main.c | 28 +++++++++++++++++++++------- 3 files changed, 24 insertions(+), 10 deletions(-) diff --git a/headers/philo_proto.h b/headers/philo_proto.h index 96652b4..a97cd0d 100644 --- a/headers/philo_proto.h +++ b/headers/philo_proto.h @@ -2,7 +2,7 @@ # define PHILO_PROTO_H // init.c -t_philo *init(char **av, pthread_t *id); +t_philo *init(char **av, pthread_t **id); #endif diff --git a/srcs/init.c b/srcs/init.c index 7bbd8ec..54b4fba 100644 --- a/srcs/init.c +++ b/srcs/init.c @@ -35,7 +35,7 @@ t_philo *init_chain_philo(t_conditions *conditions, int n) return (philo); } -t_philo *init(char **av, pthread_t *id) +t_philo *init(char **av, pthread_t **id) { t_philo *philo; t_conditions *conditions; @@ -44,7 +44,7 @@ t_philo *init(char **av, pthread_t *id) n = ft_atoi(av[1]); conditions = malloc(sizeof(t_conditions)); conditions->n_phi = n; - id = malloc(sizeof(int) * n); + *id = malloc(sizeof(int) * n); philo = init_chain_philo(conditions, n); return (philo); } diff --git a/srcs/main.c b/srcs/main.c index 13fcb72..a57525e 100644 --- a/srcs/main.c +++ b/srcs/main.c @@ -1,5 +1,7 @@ #include "philo.h" +pthread_mutex_t mutex; + void *philo_exec(void *arg) { t_philo *philo; @@ -7,29 +9,41 @@ void *philo_exec(void *arg) philo = (t_philo*)arg; nbr = philo->philo_nbr; + + pthread_mutex_lock(&mutex); + write(1, "-", 1); ft_putnbr_fd(nbr, 1); write(1, "\n", 1); + pthread_mutex_unlock(&mutex); + return (NULL); } int main(int ac, char **av) { - pthread_t id; + pthread_t *id; t_philo *philo; + int i; int n; if (ac == 1) return (0); philo = init(av, &id); - + i = 0; n = philo->conditions->n_phi; - while (n) + pthread_mutex_init(&mutex, NULL); + while (i < n) { - pthread_create(&id, NULL, &philo_exec, philo); + pthread_create(&id[i], NULL, &philo_exec, philo); philo = philo->next; - n--; + i++; } -// while (1) - write(1, "main function\n", 14); + i = 0; + while (i < n) + { + pthread_join(id[i], NULL); + i++; + } + write(1, "main function\n", 14); return 0; }