summaryrefslogtreecommitdiff
path: root/src/threads.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/threads.c')
-rw-r--r--src/threads.c93
1 files changed, 93 insertions, 0 deletions
diff --git a/src/threads.c b/src/threads.c
new file mode 100644
index 0000000..4d8776d
--- /dev/null
+++ b/src/threads.c
@@ -0,0 +1,93 @@
+#include "codexion.h"
+# include <stdlib.h> // for atoi(), malloc()
+
+void *routine(void *arg)
+{
+ t_philo *philo;
+ int number_of_eat_required;
+
+ philo = (t_philo *)arg;
+ if (philo->sim->number_of_philos == 1)
+ {
+ print_log(philo, "has taken a fork", 0);
+ return (0);
+ }
+ (void)pthread_mutex_lock(&philo->sim->mutex_number_of_eat_required);
+ number_of_eat_required = philo->sim->number_of_eat_required;
+ (void)pthread_mutex_unlock(&philo->sim->mutex_number_of_eat_required);
+ while (philo->number_of_eats_done != number_of_eat_required)
+ {
+ (void)pthread_mutex_lock(&philo->sim->mutex_number_of_eat_required);
+ number_of_eat_required = philo->sim->number_of_eat_required;
+ (void)pthread_mutex_unlock(&philo->sim->mutex_number_of_eat_required);
+ if (philo_routine(philo, philo->right_fork, philo->left_fork) != 0)
+ return (NULL);
+ }
+ return (0);
+}
+
+int create_threads(t_sim *sim)
+{
+ t_philo **philos;
+ int number_of_philos;
+ t_philo *philo;
+
+ philos = sim->philos;
+ number_of_philos = sim->number_of_philos;
+ if (pthread_create(&sim->monitor_thread, NULL, monitoring_routine,
+ sim) != 0)
+ {
+ free_philos(sim);
+ free(sim);
+ return (1);
+ }
+ while (number_of_philos-- > 0)
+ {
+ philo = *philos++;
+ if (pthread_create(&philo->thread_id, NULL, routine, philo) != 0)
+ {
+ free_philos(sim);
+ free(sim);
+ return (1);
+ }
+ }
+ return (0);
+}
+
+int join_threads(t_sim *sim)
+{
+ t_philo **philos;
+ t_philo *philo;
+ int threads;
+
+ philos = sim->philos;
+ threads = sim->number_of_philos;
+ while (threads-- > 0)
+ {
+ philo = *philos++;
+ if (pthread_join(philo->thread_id, NULL) != 0)
+ {
+ free_philos(sim);
+ free_forks(sim);
+ free(sim);
+ return (1);
+ }
+ }
+ if (pthread_join(sim->monitor_thread, NULL) != 0)
+ {
+ free_philos(sim);
+ free_forks(sim);
+ free(sim);
+ return (1);
+ }
+ return (0);
+}
+
+int run_threads(t_sim *sim)
+{
+ if (create_threads(sim) != 0)
+ return (1);
+ if (join_threads(sim) != 0)
+ return (1);
+ return (0);
+}