-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime_keeping.c
64 lines (57 loc) · 1.96 KB
/
time_keeping.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* time_keeping.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vsimeono <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/22 19:28:08 by vsimeono #+# #+# */
/* Updated: 2022/05/25 15:16:29 by vsimeono ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosophers.h"
void check_if_dead(t_game *game, t_philosopher *philosopher)
{
int miliseconds;
pthread_mutex_lock(&(philosopher->m_eat));
miliseconds = get_clock(game);
if (miliseconds > philosopher->last_meal + game->time_to_die)
{
game->end = 1;
print(philosopher, miliseconds, "died");
pthread_mutex_unlock(&(philosopher->m_eat));
}
else
{
pthread_mutex_unlock(&(philosopher->m_eat));
game->end = -1;
}
}
int get_clock(t_game *game)
{
struct timeval current_time;
int miliseconds;
gettimeofday(&(current_time), NULL);
if ((game->start).tv_usec < current_time.tv_usec)
{
miliseconds = (current_time.tv_usec - (game->start).tv_usec) / 1000;
miliseconds += (current_time.tv_sec - (game->start).tv_sec) * 1000;
}
else
{
miliseconds = 1000 + \
(current_time.tv_usec - (game->start).tv_usec) / 1000;
miliseconds += \
(current_time.tv_sec - (game->start).tv_sec - 1) * 1000;
}
return (miliseconds);
}
void wake_up(t_game *game, int seconds)
{
int wake;
wake = get_clock(game) + seconds;
while (game->end == -1 && get_clock(game) < wake)
{
usleep(50);
}
}