-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
69 lines (63 loc) · 2.47 KB
/
utils.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rtavabil <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/03/12 14:07:52 by rtavabil #+# #+# */
/* Updated: 2024/03/21 18:43:59 by rtavabil ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosophers.h"
long gettime(char *str)
{
struct timeval tv;
if (gettimeofday(&tv, NULL))
exit (1);
if (ft_strncmp(str, "sec", 4) == 0)
return (tv.tv_sec + tv.tv_usec / 1e6);
else if (ft_strncmp(str, "milli", 6) == 0)
return (tv.tv_sec * 1e3 + tv.tv_usec / 1e3);
else if (ft_strncmp(str, "micro", 6) == 0)
return (tv.tv_sec * 1e6 + tv.tv_usec);
return (1);
}
void ft_usleep(long time, t_args *args)
{
long start;
long rem;
start = gettime("micro");
while (gettime("micro") - start < time)
{
if (get_bool(&args->args_mutex, &args->end))
break ;
rem = time - (gettime("micro") - start);
if (rem > 1e3)
usleep(rem / 2);
else
while (gettime("micro") - start < time)
;
}
}
void ft_print(t_philo *philo, char *str)
{
ft_mutex(&philo->args->pr_mutex, "lock");
if (!ft_strncmp("eat", str, 4) && !philo->args->end)
printf("%ld %d is eating\n", gettime("milli") \
- philo->args->start, philo->index);
if (!ft_strncmp("sleep", str, 6) && !philo->args->end)
printf("%ld %d is sleeping\n", gettime("milli") \
- philo->args->start, philo->index);
if (!ft_strncmp("think", str, 6) && !philo->args->end)
printf("%ld %d is thinking\n", gettime("milli") \
- philo->args->start, philo->index);
if (!ft_strncmp("fork", str, 5) && !philo->args->end)
printf("%ld %d has taken a fork\n", gettime("milli") \
- philo->args->start, philo->index);
if (!ft_strncmp("died", str, 5) && \
get_bool(&philo->args->args_mutex, &philo->args->end))
printf("%ld %d died\n", gettime("milli") - \
philo->args->start, philo->index);
ft_mutex(&philo->args->pr_mutex, "unlock");
}