2023-04-13 09:00:39 -04:00
|
|
|
#include <pthread.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stddef.h>
|
2023-04-19 07:53:50 -04:00
|
|
|
#include <stdio.h>
|
2023-04-13 09:00:39 -04:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include "./philos.h"
|
|
|
|
#include "./data.h"
|
|
|
|
#include "./parsing.h"
|
|
|
|
#include "./threads.h"
|
|
|
|
#include "./time.h"
|
|
|
|
#include "./print.h"
|
|
|
|
#include "./struct.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];
|
2023-04-19 07:59:37 -04:00
|
|
|
pthread_mutex_lock(&philo->nb_meal_mutex);
|
2023-04-13 09:00:39 -04:00
|
|
|
min = philo->nb_meal;
|
2023-04-19 07:59:37 -04:00
|
|
|
pthread_mutex_unlock(&philo->nb_meal_mutex);
|
2023-04-13 09:00:39 -04:00
|
|
|
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);
|
|
|
|
}
|
|
|
|
|
|
|
|
void check_routine(t_data *data)
|
|
|
|
{
|
|
|
|
size_t i;
|
|
|
|
bool ok;
|
|
|
|
t_philo *philo;
|
|
|
|
|
|
|
|
while (true)
|
|
|
|
{
|
|
|
|
if ((ssize_t) get_min_meal(data) == data->nb_meals)
|
2023-04-19 07:53:50 -04:00
|
|
|
{
|
|
|
|
printf("g pu faim\n");
|
2023-04-13 09:00:39 -04:00
|
|
|
stop(data);
|
2023-04-19 07:53:50 -04:00
|
|
|
return ;
|
|
|
|
}
|
2023-04-13 09:00:39 -04:00
|
|
|
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)
|
|
|
|
{
|
|
|
|
print_died(philo);
|
|
|
|
return ;
|
|
|
|
}
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
int main(int ac, char **av)
|
|
|
|
{
|
|
|
|
t_data data;
|
|
|
|
|
|
|
|
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);
|
|
|
|
}
|