summaryrefslogtreecommitdiff
path: root/src/routine.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/routine.c
Add all files, first commit
Diffstat (limited to 'src/routine.c')
-rw-r--r--src/routine.c57
1 files changed, 57 insertions, 0 deletions
diff --git a/src/routine.c b/src/routine.c
new file mode 100644
index 0000000..6d867cf
--- /dev/null
+++ b/src/routine.c
@@ -0,0 +1,57 @@
+#include "codexion.h"
+# include <unistd.h> // for usleep()
+# include <stdio.h> // for printf()
+
+static void send_signal(t_fork *fork)
+{
+ (void)pthread_mutex_lock(&fork->mutex_cond);
+ pthread_cond_signal(&fork->cond_signal);
+ (void)pthread_mutex_unlock(&fork->mutex_cond);
+}
+
+static void lock_forks(t_philo *philo, t_fork *f1,
+ t_fork *f2)
+{
+ if (get_id(philo) % 2 == 0)
+ {
+ (void)pthread_mutex_lock(&f1->mutex);
+ (void)pthread_mutex_lock(&f2->mutex);
+ }
+ else
+ {
+ if (philo->number_of_eats_done < 1)
+ usleep(50);
+ (void)pthread_mutex_lock(&f2->mutex);
+ (void)pthread_mutex_lock(&f1->mutex);
+ }
+ wait_for_longest_cooldown(philo, f1, f2);
+}
+
+int philo_routine(t_philo *philo, t_fork *f1,
+ t_fork *f2)
+{
+ t_sim *sim;
+
+ (void)pthread_mutex_lock(&philo->mutex_sim);
+ sim = philo->sim;
+ (void)pthread_mutex_unlock(&philo->mutex_sim);
+ if (check_if_philo_starved(sim))
+ return (1);
+ if (queue_routine(philo, f1, f2) == 1)
+ return (1);
+ if (check_if_philo_starved(sim))
+ return (1);
+ lock_forks(philo, f1, f2);
+ print_log(philo, "has taken a fork", 0);
+ print_log(philo, "has taken a fork", 0);
+ update_last_released(sim, f1, f2);
+ eat(philo);
+ (void)pthread_mutex_unlock(&f2->mutex);
+ dequeue(f2);
+ send_signal(f2);
+ (void)pthread_mutex_unlock(&f1->mutex);
+ dequeue(f1);
+ send_signal(f1);
+ reflect_and_think(philo);
+ return (0);
+}