#include "codexion.h" # include // 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); }