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
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/11/24 05:53:02 by cacharle #+# #+# */
/* Updated: 2021/01/10 09:33:17 by cacharle ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_one.h"
static int st_setup(
t_philo_conf *conf,
t_philo **philos,
pthread_mutex_t **forks)
{
if ((*forks = forks_new(conf->philo_num)) == NULL)
return (1);
if ((*philos = philos_new(conf, *forks)) == NULL)
{
forks_destroy(*forks, conf->philo_num);
return (1);
}
if (pthread_mutex_init(&conf->mutex_stdout, NULL) != 0)
{
forks_destroy(*forks, conf->philo_num);
free(*philos);
return (1);
}
if (pthread_mutex_init(&conf->mutex_meal_num_finished_counter, NULL) != 0)
{
forks_destroy(*forks, conf->philo_num);
free(*philos);
pthread_mutex_destroy(&conf->mutex_stdout);
return (1);
}
conf->all_alive = true;
conf->meal_num_finished_counter = 0;
return (0);
}
void *routine_flush(t_philo_conf *conf)
{
while (true)
{
pthread_mutex_lock(&conf->mutex_stdout);
philo_put_flush();
pthread_mutex_unlock(&conf->mutex_stdout);
usleep(250000);
}
}
int main(int argc, char **argv)
{
t_philo_conf conf;
t_philo *philos;
pthread_mutex_t *forks;
if (!parse_args((t_philo_args*)&conf, argc, argv))
return (1);
if (conf.philo_num == 0 || conf.meal_num == 0)
return (0);
if (st_setup(&conf, &philos, &forks) != 0)
return (1);
pthread_t thread_flush;
pthread_create(&thread_flush, NULL, (t_routine)routine_flush, (void*)&conf);
pthread_detach(thread_flush);
conf.initial_time = h_time_now();
if (!philos_start(philos, conf.philo_num))
{
forks_destroy(forks, conf.philo_num);
free(philos);
return (1);
}
while (!philo_finished(&conf))
usleep(500);
philo_put_flush();
philos_detach(philos, conf.philo_num);
forks_destroy(forks, conf.philo_num);
pthread_mutex_destroy(&conf.mutex_stdout);
pthread_mutex_destroy(&conf.mutex_meal_num_finished_counter);
free(philos);
return (0);
}
|