aboutsummaryrefslogtreecommitdiff
path: root/philo_one/src/forks.c
diff options
context:
space:
mode:
authorCharles Cabergs <me@cacharle.xyz>2020-09-29 14:56:27 +0200
committerCharles Cabergs <me@cacharle.xyz>2020-09-29 14:56:27 +0200
commit6bfcd3c6f921e7717e61167b291bb27bd3f66386 (patch)
tree67b2aa4b8a036cb355f90b1f94438b7eb46441f1 /philo_one/src/forks.c
parentac4278405b7a258010219499cccc0dd978201caf (diff)
downloadphilosophers-6bfcd3c6f921e7717e61167b291bb27bd3f66386.tar.gz
philosophers-6bfcd3c6f921e7717e61167b291bb27bd3f66386.tar.bz2
philosophers-6bfcd3c6f921e7717e61167b291bb27bd3f66386.zip
Fixing taking none existing fork in logs
Diffstat (limited to 'philo_one/src/forks.c')
-rw-r--r--philo_one/src/forks.c60
1 files changed, 60 insertions, 0 deletions
diff --git a/philo_one/src/forks.c b/philo_one/src/forks.c
new file mode 100644
index 0000000..ebe5261
--- /dev/null
+++ b/philo_one/src/forks.c
@@ -0,0 +1,60 @@
+/* ************************************************************************** */
+/* */
+/* ::: :::::::: */
+/* forks.c :+: :+: :+: */
+/* +:+ +:+ +:+ */
+/* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */
+/* +#+#+#+#+#+ +#+ */
+/* Created: 2020/02/09 23:46:40 by cacharle #+# #+# */
+/* Updated: 2020/09/27 09:26:12 by charles ### ########.fr */
+/* */
+/* ************************************************************************** */
+
+#include "philo_one.h"
+
+pthread_mutex_t *forks_new(int num)
+{
+ int i;
+ pthread_mutex_t *forks;
+
+ if ((forks = malloc(num * sizeof(pthread_mutex_t))) == NULL)
+ return (NULL);
+ i = -1;
+ while (++i < num)
+ {
+ if (pthread_mutex_init(&forks[i], NULL) != 0)
+ {
+ forks_destroy(forks, i + 1);
+ return (NULL);
+ }
+ }
+ return (forks);
+}
+
+void forks_destroy(pthread_mutex_t *forks, int num)
+{
+ while (num-- > 0)
+ pthread_mutex_destroy(&forks[num]);
+ free(forks);
+}
+
+t_routine_arg *forks_dispatch(
+ t_philo *philos,
+ pthread_mutex_t *forks,
+ t_philo_conf *conf)
+{
+ int i;
+ t_routine_arg *routine_args;
+
+ if ((routine_args = malloc(conf->philo_num * sizeof(t_routine_arg))) == NULL)
+ return (NULL);
+ i = -1;
+ while (++i < conf->philo_num)
+ {
+ routine_args[i].conf = conf;
+ routine_args[i].philo = philos + i;
+ routine_args[i].fork_left = forks + i % conf->philo_num;
+ routine_args[i].fork_right = forks + (i + 1) % conf->philo_num;
+ }
+ return (routine_args);
+}