/* By: ljiriste <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/03/22 11:19:48 by ljiriste #+# #+# */
-/* Updated: 2024/05/10 11:03:38 by ljiriste ### ########.fr */
+/* Updated: 2024/05/10 11:42:24 by ljiriste ### ########.fr */
/* */
/* ************************************************************************** */
#include <limits.h>
#include <stdio.h>
-static int seat_philosophers(t_diner *diner, pthread_t *threads)
+static int seat_philosophers(t_settings *settings, pid_t *philo_pids)
{
- size_t i;
+ t_philo philo;
- gettimeofday(&diner->setting.start, NULL);
- i = 0;
- while (i < diner->setting.philo_count)
+ philo.num_eaten = 0;
+ gettimeofday(&settings->start, NULL);
+ philo.settings = *settings;
+ philo.id = 1;
+ while (philo.id <= setting->philo_count)
{
- if (pthread_create(threads + i, NULL,
- be_a_philosopher, diner->philos + i))
+ philo_pids[philo.id - 1] = fork();
+ if (philo_pids[philo.id - 1] == 0)
{
- mutex_lock(&diner->setting.end_lock);
- diner->setting.end = 1;
- mutex_unlock(&diner->setting.end_lock);
- while (i > 0)
- {
- pthread_join(threads[--i], NULL);
- }
- return (1);
+ free(philo_pids);
+ be_a_philosopher(*philo);
}
- ++i;
- }
- return (0);
-}
-
-static int is_dead(t_philo *philo)
-{
- mutex_lock(&philo->philo_lock);
- if (usecs_since_start(philo->settings->start) - philo->last_eaten
- > philo->settings->time_to_die)
- {
- mutex_unlock(&philo->philo_lock);
- return (1);
+ else if (philo_pids[philo.id - 1] < 0)
+ return (1);
+ ++philo.id;
}
- mutex_unlock(&philo->philo_lock);
return (0);
}
-static int all_full(t_diner *diner)
-{
- size_t i;
- unsigned int min_eaten;
-
- if (!diner->setting.should_check_hunger)
- return (0);
- i = 0;
- min_eaten = UINT_MAX;
- while (i < diner->setting.philo_count)
- {
- mutex_lock(&diner->philos[i].philo_lock);
- if (min_eaten > diner->philos[i].num_eaten)
- min_eaten = diner->philos[i].num_eaten;
- mutex_unlock(&diner->philos[i].philo_lock);
- ++i;
- }
- return (min_eaten >= diner->setting.min_eat_num);
-}
-
static enum e_end watch_philosophers(t_diner *diner)
{
size_t i;
{
t_settings settings;
pid_t *philo_pids;
- sem_t *semaphores[SEM_NUM];
+ sem_t *semaphores[sem_num];
if (parse_input(&settings, argc, argv))
{
cleanup(philo_pids, semaphores);
return (2);
}
- if (seat_philosophers(settings, philo_pids))
+ if (seat_philosophers(*settings, philo_pids))
{
+ kill_philosophers(setings.philo_count, philo_pids);
cleanup(philo_pids, semaphores);
return (3);
}
+ sem_post(semaphores[term]);
handle_philosophers(semaphores);
cleanup(philo_pids, semaphores);
return (0);