2021-05-16 01:41:18 +03:00

107 lines
2.3 KiB
C

#include "../includes/philo_header.h"
void *run_trhead(t_philo *philo)
{
philo->worked = 1;
while(1)
{
if (philo->can_run_simulation)
break;
}
if (philo->can_run_simulation)
{
while(philo->can_run_simulation && philo->all_struct->smert != 42)
{
if (philo->all_struct->opt)
{
if (philo->count_eat == philo->all_struct->number_of_times_each_philosopher_must_eat)
{
philo->all_struct->smert = 42; // TODO реализовать завершение программы
}
}
cycle(philo);
}
}
return(NULL);
}
void take_forks(t_philo *philo)
{
t_all *all;
all = philo->all_struct;
pthread_mutex_lock(&all->data_philo->mutex[philo->less_fork]);
messages(philo->all_struct, philo, "has taken a fork");
pthread_mutex_lock(&all->data_philo->mutex[philo->more_fork]);
messages(philo->all_struct, philo, "has taken a fork");
}
void eating(t_philo *philo)
{
messages(philo->all_struct, philo, "eating");
philo->last_eat = ft_get_time() - philo->all_struct->start_time;
ft_msleep(philo->all_struct->time_to_eat);
philo->count_eat++;
}
void sleeping(t_philo *philo)
{
t_all *all;
all = philo->all_struct;
messages(philo->all_struct, philo, "sleeping");
pthread_mutex_unlock(&all->data_philo->mutex[philo->more_fork]);
pthread_mutex_unlock(&all->data_philo->mutex[philo->less_fork]);
ft_msleep(philo->all_struct->time_to_sleep);
}
void cycle(t_philo *philo)
{
messages(philo->all_struct, philo, "thinking");
take_forks(philo);
eating(philo);
sleeping(philo);
}
int run_observer(t_all *all)
{
int i;
i = 0;
time_t time_eat;
while(1)
{
i = 0;
while(i <= all->number_of_philosophers)
{
if (all->smert != 42)
{
time_eat = (ft_get_time() - all->start_time) - all->data_philo->philors[i].last_eat;
if (time_eat > all->time_to_die) // TODO пофиксить смерть
{
printf("%ld---------------симуляция окончена фил %d умер ---------------\n", ft_get_time() - all->start_time, i + 1);
return(2);
}
}
else
{
return(2);
}
i++;
}
}
return (0);
}
int runner(t_all *all)
{
prepare_resources(all);
run_all_phils(all);
if (check_all_run(all))
{
all->start_time = ft_get_time();
run_simulation(all);
}
if (!run_observer(all))
{
return(0);
}
return(1);
}