-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvisor_routine.c
82 lines (76 loc) · 2.31 KB
/
visor_routine.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* visor_routine.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: pscala <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/03 16:14:57 by pscala #+# #+# */
/* Updated: 2024/08/05 13:14:59 by pscala ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosopher.h"
int check_if_dead(t_philo *philo)
{
if (get_time() - philo->last_meal > philo->args->time_to_die)
{
pthread_mutex_lock(&philo->args->deadmutex);
philo->args->dead = 1;
pthread_mutex_unlock(&philo->args->deadmutex);
return (ft_print(philo, "died 💀 *rip*\n", RED), -1);
}
return (0);
}
void ft_wait_again(t_philo *philos)
{
while (1)
{
pthread_mutex_lock(&philos->args->mutex_philo_in_queue);
if (philos->args->philo_in_queue == philos->args->nb_of_philo)
{
pthread_mutex_unlock(&philos->args->mutex_philo_in_queue);
break ;
}
pthread_mutex_unlock(&philos->args->mutex_philo_in_queue);
usleep(500);
}
usleep(500);
}
void visor_loop(t_philo *philos, int i, int complete)
{
while (1)
{
pthread_mutex_lock(&philos[i].mealsmutex);
if (philos[i].nb_of_meals != philos->args->nb_of_time_to_eat
&& check_if_dead(&philos[i]) == -1)
{
pthread_mutex_unlock(&philos[i].mealsmutex);
break ;
}
else if (philos[i].nb_of_meals == philos->args->nb_of_time_to_eat)
complete++;
pthread_mutex_unlock(&philos[i].mealsmutex);
if (complete == philos->args->nb_of_philo)
break ;
if (i + 1 == philos->args->nb_of_philo)
{
i = 0;
complete = 0;
}
else
i++;
usleep(500);
}
}
void *visor_routine(void *thread)
{
t_philo *philos;
int i;
int complete;
philos = (t_philo *)thread;
i = 0;
complete = 0;
ft_wait_again(philos);
visor_loop(philos, i, complete);
return (NULL);
}