aboutsummaryrefslogtreecommitdiff
path: root/philo_one/src/philo.c
diff options
context:
space:
mode:
Diffstat (limited to 'philo_one/src/philo.c')
-rw-r--r--philo_one/src/philo.c42
1 files changed, 20 insertions, 22 deletions
diff --git a/philo_one/src/philo.c b/philo_one/src/philo.c
index 8a41fe7..1e8e691 100644
--- a/philo_one/src/philo.c
+++ b/philo_one/src/philo.c
@@ -6,13 +6,13 @@
/* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/09 23:47:14 by cacharle #+# #+# */
-/* Updated: 2021/01/10 09:49:48 by cacharle ### ########.fr */
+/* Updated: 2021/01/10 11:50:43 by cacharle ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_one.h"
-t_philo *philos_new(t_philo_conf *conf, pthread_mutex_t *forks)
+t_philo *philos_new(t_philo_conf *conf)
{
long int i;
t_philo *philos;
@@ -26,11 +26,15 @@ t_philo *philos_new(t_philo_conf *conf, pthread_mutex_t *forks)
{
philos[i].id = i + 1;
philos[i].conf = conf;
- philos[i].fork_left = forks + i % conf->philo_num;
- philos[i].fork_right = forks + (i + 1) % conf->philo_num;
- pthread_mutex_init(&philos[i].mutex_start, NULL);
+ philos[i].fork_left = conf->forks + i % conf->philo_num;
+ philos[i].fork_right = conf->forks + (i + 1) % conf->philo_num;
+ if (pthread_mutex_init(&philos[i].mutex_start, NULL) != 0 ||
+ pthread_mutex_init(&philos[i].mutex_eat, NULL) != 0)
+ {
+ philos_destroy(philos, i);
+ return (false);
+ }
pthread_mutex_lock(&philos[i].mutex_start);
- pthread_mutex_init(&philos[i].mutex_eat, NULL);
}
return (philos);
}
@@ -47,32 +51,21 @@ bool philos_start(t_philo *philos, long int num)
NULL,
(t_routine)routine_philo,
(void*)(philos + i)) != 0)
- {
- while (--i >= 0)
- pthread_detach(philos[i].thread);
return (false);
- }
}
i = -1;
while (++i < num)
- {
- if (i % 2 == 0)
- continue;
- pthread_mutex_unlock(&philos[i].mutex_start);
- }
+ if (i % 2 == 1)
+ pthread_mutex_unlock(&philos[i].mutex_start);
usleep(1000);
i = -1;
while (++i < num)
- {
- if (i % 2 == 1)
- continue;
- pthread_mutex_unlock(&philos[i].mutex_start);
- }
-
+ if (i % 2 == 0)
+ pthread_mutex_unlock(&philos[i].mutex_start);
return (true);
}
-void philos_detach(t_philo *philos, long int num)
+void philos_destroy(t_philo *philos, long int num)
{
long int i;
@@ -80,5 +73,10 @@ void philos_detach(t_philo *philos, long int num)
return ;
i = -1;
while (++i < num)
+ {
+ pthread_mutex_destroy(&philos[i].mutex_start);
+ pthread_mutex_destroy(&philos[i].mutex_eat);
pthread_detach(philos[i].thread);
+ }
+ free(philos);
}