-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.c
98 lines (88 loc) · 2.81 KB
/
init.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* init.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: plpelleg <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/28 20:47:28 by plpelleg #+# #+# */
/* Updated: 2021/12/03 19:53:28 by plpelleg ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
void ft_init_philo(pthread_mutex_t *forks, t_param *parameters,
t_philo *philosopher)
{
int id;
pthread_mutex_t *tmp;
id = -1;
while (++id < parameters ->n_philo)
{
philosopher[id].id = id;
philosopher[id].num_times_eaten = 0;
philosopher[id].parameters = parameters;
philosopher[id].left_fork = &forks[id];
if (!id)
philosopher[id].right_fork = &forks[parameters->n_philo - 1];
else
philosopher[id].right_fork = &forks[id - 1];
if (id % 2 == 1)
{
tmp = philosopher[id].left_fork;
philosopher[id].left_fork = philosopher[id].right_fork;
philosopher[id].right_fork = tmp;
}
}
}
void ft_initialize_mutex(t_param *parameters, pthread_mutex_t *mutex_array)
{
int i;
i = -1;
while (++i < parameters ->n_philo)
pthread_mutex_init(&mutex_array[i], NULL);
}
void ft_generate_threads(t_param *parameters, pthread_t *threads,
t_philo *philosophers)
{
int i;
i = -1;
while (++i < parameters ->n_philo)
pthread_create(&threads[i], NULL, &ft_routine, &philosophers[i]);
}
//parsing
static void ft_set_param(int argc, char **argv, t_param *parameters)
{
if (argc > 4 && argc < 7)
{
parameters -> n_philo = ft_atoi(argv[1], parameters);
parameters -> time_to_die = ft_atoi(argv[2], parameters);
parameters -> time_to_eat = ft_atoi(argv[3], parameters);
parameters -> time_to_sleep = ft_atoi(argv[4], parameters);
if (argc == 6)
parameters -> n_times_to_eat = ft_atoi(argv[5], parameters);
else
parameters -> n_times_to_eat = -1;
}
else
parameters -> error = 2;
}
t_param *ft_parse(int argc, char **argv)
{
t_param *parameters;
parameters = malloc(sizeof(t_param));
if (!parameters)
{
write(1, "MALLOC ERROR\n", 14);
ft_exit(parameters, NULL, NULL, NULL);
return (NULL);
}
parameters -> error = 0;
ft_set_param(argc, argv, parameters);
if (parameters -> error)
{
ft_set_error(parameters);
ft_exit(parameters, NULL, NULL, NULL);
return (NULL);
}
return (parameters);
}