42_Philosopher/philo/main.c
Camille Chauvet f88abe9631 dsfsd
2023-05-25 17:31:02 +02:00

117 lines
2.6 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/04/27 11:33:25 by cchauvet #+# #+# */
/* Updated: 2023/05/25 16:34:22 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include <pthread.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "./philos.h"
#include "./data.h"
#include "./parsing.h"
#include "./threads.h"
#include "./time.h"
#include "./print.h"
#include "./utils/utils.h"
size_t get_min_meal(t_data *data)
{
size_t i;
size_t min;
size_t value;
t_philo *philo;
philo = data->philos[0];
pthread_mutex_lock(&philo->nb_meal_mutex);
min = philo->nb_meal;
pthread_mutex_unlock(&philo->nb_meal_mutex);
i = 1;
while (i < data->nb_philos)
{
philo = data->philos[i];
pthread_mutex_lock(&philo->nb_meal_mutex);
value = philo->nb_meal;
pthread_mutex_unlock(&philo->nb_meal_mutex);
if (min > value)
min = value;
i++;
}
return (min);
}
void stop(t_data *data)
{
pthread_mutex_lock(&data->stop_mutex);
data->stop = 1;
pthread_mutex_unlock(&data->stop_mutex);
}
int routine(t_data *data)
{
size_t i;
bool ok;
t_philo *philo;
i = 0;
while (i < data->nb_philos)
{
philo = data->philos[i];
pthread_mutex_lock(&philo->last_eat_mutex);
ok = !(philo->last_eat + data->life_expectency > get_time());
pthread_mutex_unlock(&philo->last_eat_mutex);
if (ok == 1)
{
stop(data);
print_died(philo);
return (1);
}
i++;
}
return (0);
}
void *check_routine(t_data *data)
{
while (data->stop == 0)
{
if (routine(data))
{
return (NULL);
}
}
return (NULL);
}
int main(int ac, char **av)
{
t_data data;
get_time();
if (parsing(&data, av + 1, ac - 1))
return (1);
if (data_init(&data))
return (1);
if (philos_init(&data))
{
data_destroyer(&data);
return (1);
}
if (threads_init(&data))
{
data_destroyer(&data);
return (1);
}
check_routine(&data);
data_destroyer(&data);
}