-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.c
More file actions
98 lines (90 loc) · 2.79 KB
/
Copy pathmonitor.c
File metadata and controls
98 lines (90 loc) · 2.79 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
90
91
92
93
94
95
96
97
98
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* monitor.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oabdelka <oabdelka@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/09 13:35:44 by oabdelka #+# #+# */
/* Updated: 2024/12/09 13:35:44 by oabdelka ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosopher.h"
int has_any_philosopher_died(t_simulation *simulation)
{
pthread_mutex_lock(&simulation->m_died);
if (simulation->died)
{
pthread_mutex_unlock(&simulation->m_died);
return (1);
}
pthread_mutex_unlock(&simulation->m_died);
return (0);
}
int has_simulation_end(t_simulation *sim)
{
pthread_mutex_lock(&sim->m_end);
if (sim->end)
{
pthread_mutex_unlock(&sim->m_end);
return (1);
}
pthread_mutex_unlock(&sim->m_end);
return (0);
}
static int have_all_philosophers_eaten(t_philo *philo)
{
pthread_mutex_lock(&philo->simulation->eat);
if (philo->eat_count >= philo->simulation->meals_required)
{
pthread_mutex_unlock(&philo->simulation->eat);
return (1);
}
pthread_mutex_unlock(&philo->simulation->eat);
return (0);
}
static void check_end_condition(t_simulation *simulation)
{
int i;
i = 0;
while (simulation->meals_required != -1 && i < simulation->num_philosophers
&& have_all_philosophers_eaten(&simulation->philo[i]))
i++;
if (i == simulation->num_philosophers)
{
pthread_mutex_lock(&simulation->m_end);
simulation->end = 1;
pthread_mutex_unlock(&simulation->m_end);
pthread_mutex_lock(&simulation->print);
printf("number of meals eaten: %d\n",
simulation->meals_required);
pthread_mutex_unlock(&simulation->print);
}
}
void monitor_death(t_simulation *simulation)
{
int i;
while (!has_simulation_end(simulation))
{
i = -1;
while (
++i < simulation->num_philosophers
&& !has_any_philosopher_died(simulation)
)
{
pthread_mutex_lock(&simulation->meal);
if (
(current_timestamp() - simulation->philo[i].lastmeal)
> simulation->time_to_die
)
{
handle_philosopher_death(simulation, i);
}
pthread_mutex_unlock(&simulation->meal);
usleep(200);
}
if (has_any_philosopher_died(simulation))
break ;
check_end_condition(simulation);
}
}