127 lines
2.4 KiB
C
127 lines
2.4 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)
|
|
{
|
|
philo->last_eat = ft_get_time();
|
|
philo->limit = philo->last_eat + philo->all_struct->time_to_die;
|
|
while(philo->can_run_simulation)
|
|
{
|
|
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)
|
|
{
|
|
pthread_mutex_lock(&philo->eat_mutex);
|
|
philo->last_eat = ft_get_time();
|
|
philo->limit = philo->last_eat + philo->all_struct->time_to_die;
|
|
messages(philo->all_struct, philo, "eating");
|
|
usleep(philo->all_struct->time_to_eat * 1000);
|
|
philo->count_eat++;
|
|
pthread_mutex_unlock(&philo->eat_mutex);
|
|
}
|
|
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]);
|
|
usleep(philo->all_struct->time_to_sleep * 1000);
|
|
}
|
|
|
|
|
|
void cycle(t_philo *philo)
|
|
{
|
|
take_forks(philo);
|
|
eating(philo);
|
|
sleeping(philo);
|
|
messages(philo->all_struct, philo, "thinking");
|
|
}
|
|
|
|
|
|
int run_observer(t_all *all)
|
|
{
|
|
int i;
|
|
int died;
|
|
time_t time;
|
|
|
|
i = 0;
|
|
died = 0;
|
|
time = ft_get_time();
|
|
while(1)
|
|
{
|
|
i = 0;
|
|
while(i <= all->number_of_philosophers)
|
|
{
|
|
|
|
if (!all->data_philo->philors[i].is_eat && ft_get_time() > all->data_philo->philors[i].limit)
|
|
{
|
|
// TODO пофиксить смерть
|
|
printf("симуляция окончена фил умер\n");
|
|
exit(0);
|
|
}
|
|
|
|
if (all->data_philo->philors[i].died == 0)
|
|
{
|
|
time = ft_get_time();
|
|
i++;
|
|
}
|
|
else
|
|
{
|
|
died = 42;
|
|
break;
|
|
}
|
|
}
|
|
if (died == 42)
|
|
{
|
|
printf("симуляция окончена фил умер\n");
|
|
break;
|
|
}
|
|
}
|
|
return (0);
|
|
}
|
|
|
|
|
|
int runner(t_all *all, int optional)
|
|
{
|
|
if (optional)
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
return(1);
|
|
}
|
|
return(1);
|
|
}
|