-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.c
More file actions
89 lines (81 loc) · 2.41 KB
/
Copy pathmonitor.c
File metadata and controls
89 lines (81 loc) · 2.41 KB
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
83
84
85
86
87
88
89
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* monitor.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jsaintho <jsaintho@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/23 17:29:22 by jsaintho #+# #+# */
/* Updated: 2024/09/25 17:02:52 by jsaintho ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
// CHECK [ONE] PHILO DEATH
int philosopher_dead(t_philo *philo, int time_to_die)
{
pthread_mutex_lock(&philo->info->eat_lock);
if (timestamp() - philo->last_meal >= time_to_die && philo->eating == 0)
{
return (pthread_mutex_unlock(&philo->info->eat_lock), 1);
}
pthread_mutex_unlock(&philo->info->eat_lock);
return (0);
}
// CHECK [ANY] PHILO DEATH
int check_if_dead(t_philo *philos, int n, int d)
{
int i;
i = 0;
while (i < n)
{
if (philosopher_dead(&philos[i], d))
{
t_print(&philos[i], "died\n");
pthread_mutex_lock(&philos[0].info->dead_lock);
philos[0].dead = 1;
pthread_mutex_unlock(&philos[0].info->dead_lock);
return (1);
}
i++;
}
return (0);
}
// Checks if all the philos ate the num_of_meals
int check_if_all_ate(t_philo *philos)
{
int i;
int finished_eating;
i = 0;
finished_eating = 0;
if (philos[0].info->n_eat < 0)
return (0);
while (i < philos[0].info->n_philo)
{
pthread_mutex_lock(&philos[i].info->eat_lock);
if (philos[i].eaten_meal >= philos[i].info->n_eat)
finished_eating++;
pthread_mutex_unlock(&philos[i].info->eat_lock);
i++;
}
if (finished_eating == philos[0].info->n_philo)
{
pthread_mutex_lock(&philos[0].info->dead_lock);
philos[0].dead = 1;
pthread_mutex_unlock(&philos[0].info->dead_lock);
return (1);
}
return (0);
}
void *monitor(void *p)
{
t_info *td;
td = (t_info *)p;
while (1)
{
if (check_if_dead(td->philosophers, td->n_philo, td->t_die) == 1
|| (check_if_all_ate(td->philosophers) == 1))
break ;
usleep(1);
}
return (p);
}