summaryrefslogtreecommitdiff
path: root/src/forks.c
diff options
context:
space:
mode:
authoryctct <yctct@yctct.com>2026-09-13 18:58:14 +0200
committeryctct <yctct@yctct.com>2026-09-13 18:58:14 +0200
commit47beba686ff9d2aab63738fba7176a5235703d05 (patch)
treef839ed36a9e9d4476fcdc59379b17903abfa35c8 /src/forks.c
Add all files, first commit
Diffstat (limited to 'src/forks.c')
-rw-r--r--src/forks.c75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/forks.c b/src/forks.c
new file mode 100644
index 0000000..534ccc4
--- /dev/null
+++ b/src/forks.c
@@ -0,0 +1,75 @@
+#include "codexion.h"
+# include <stdlib.h> // for atoi(), malloc()
+
+/*
+fork's last used is a negative value of waiting time so first philos can
+start compiling at the start of the simulation
+*/
+
+t_fork *create_fork(t_sim *sim)
+{
+ t_fork *fork;
+ t_queue pq;
+
+ fork = (t_fork *)malloc(sizeof(t_fork));
+ if (!fork)
+ {
+ free_forks(sim);
+ free(sim);
+ return (NULL);
+ }
+ fork->last_released = -1 * sim->fork_cooldown;
+ fork->ticket_next = 1;
+ fork->sim = sim;
+ pq.size = 0;
+ fork->pq = pq;
+ return (fork);
+}
+
+t_fork **create_arr_forks(t_sim *sim)
+{
+ t_fork **forks;
+ t_fork *fork;
+ int i;
+ int number_of_philos;
+
+ i = 0;
+ number_of_philos = sim->number_of_philos;
+ forks = (t_fork **)malloc((sizeof(t_fork *) * (number_of_philos
+ + 1)));
+ if (!forks)
+ {
+ free(sim);
+ return (NULL);
+ }
+ while (number_of_philos-- > 0)
+ {
+ fork = create_fork(sim);
+ fork->id = i + 1;
+ forks[i++] = fork;
+ }
+ forks[i] = NULL;
+ sim->number_of_forks_actual = i;
+ sim->forks = forks;
+ return (forks);
+}
+
+t_philo **assign_forks(t_sim *sim)
+{
+ t_philo **philos;
+ t_fork **forks;
+ int number_of_philos;
+ int i;
+
+ philos = sim->philos;
+ forks = sim->forks;
+ number_of_philos = sim->number_of_philos;
+ i = 0;
+ while (philos[i])
+ {
+ philos[i]->left_fork = forks[i];
+ philos[i]->right_fork = forks[(i + 1) % number_of_philos];
+ i++;
+ }
+ return (philos);
+}