-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.c
111 lines (100 loc) · 2.95 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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* utils.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ana-lda- <ana-lda-@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/08/16 09:17:55 by druina #+# #+# */
/* Updated: 2024/10/28 14:28:06 by ana-lda- ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
int ft_strlen(char *str)
{
int i;
if (str == NULL)
return (0);
i = 0;
while (str[i] != '\0')
i++;
return (i);
}
int ft_atoi(char *str)
{
unsigned long long nb;
int sign;
int i;
nb = 0;
sign = 1;
i = 0;
while (str[i] == ' ' || str[i] == '\t' || str[i] == '\n' || str[i] == '\v'
|| str[i] == '\f' || str[i] == '\r')
i++;
if (str[i] == '-')
sign = -1;
if (str[i] == '-' || str[i] == '+')
i++;
while (str[i] >= '0' && str[i] <= '9')
{
nb = nb * 10 + (str[i] - '0');
i++;
}
return (sign * nb);
}
/** @brief Destroys all the mutexes used in the program
* and handles error logging.
*
* @param str A string containing an error message to log
* (can be NULL).
* @param program A pointer to the program structure, containing
* mutexes to destroy.
* @param forks An array of mutexes representing forks used by philosophers.
*/
void destroy_all(char *str, t_program *program, pthread_mutex_t *forks)
{
int i;
i = 0;
if (str)
{
write(2, str, ft_strlen(str));
write(2, "\n", 1);
}
pthread_mutex_destroy(&program->write_lock);
pthread_mutex_destroy(&program->meal_lock);
pthread_mutex_destroy(&program->dead_lock);
while (i < program->philos[0].num_of_philos)
{
pthread_mutex_destroy(&forks[i]);
i++;
}
}
/** @brief This function repeatedly sleeps for 500 microseconds
* until the total sleep time
* reaches the specified number of milliseconds.
*
* @param milliseconds The number of milliseconds to sleep.
* @return Always returns 0.
*/
int ft_usleep(size_t milliseconds)
{
size_t start;
start = get_current_time();
while ((get_current_time() - start) < milliseconds)
usleep(500);
return (0);
}
/** @brief Gets the current time in milliseconds.
*
* This function retrieves the current time using gettimeofday,
* converts it to milliseconds, and returns the result.
*
* @return The current time in milliseconds since the Epoch.
*/
size_t get_current_time(void)
{
struct timeval time;
if (gettimeofday(&time, NULL) == -1)
write(2, "gettimeofday() error\n", 22);
return (time.tv_sec * 1000 + time.tv_usec / 1000);
}