Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
yabtaour
GitHub Repository: yabtaour/Philosophers-42
Path: blob/master/philo/ft_create_philosophers.c
882 views
1
/* ************************************************************************** */
2
/* */
3
/* ::: :::::::: */
4
/* ft_create_philosophers.c :+: :+: :+: */
5
/* +:+ +:+ +:+ */
6
/* By: yabtaour <[email protected]> +#+ +:+ +#+ */
7
/* +#+#+#+#+#+ +#+ */
8
/* Created: 2022/05/19 23:36:39 by yabtaour #+# #+# */
9
/* Updated: 2022/05/19 23:36:42 by yabtaour ### ########.fr */
10
/* */
11
/* ************************************************************************** */
12
#include "philosophers.h"
13
14
void ft_destroy(t_data *data)
15
{
16
int i;
17
18
i = 0;
19
pthread_mutex_destroy(&data->output);
20
pthread_mutex_destroy(&data->eat);
21
while (i < data->philos_num)
22
{
23
pthread_detach(data->philosopher[i].thread_id);
24
pthread_mutex_destroy(data->philosopher[i].right_fork);
25
pthread_mutex_destroy(data->philosopher[i].left_fork);
26
i++;
27
}
28
}
29
30
int ft_join_destroy(t_data *data)
31
{
32
int i;
33
34
i = 0;
35
if (ft_check_dead(data))
36
{
37
ft_destroy(data);
38
free(data);
39
return (0);
40
}
41
while (i < data->philos_num)
42
{
43
if (pthread_join(data->philosopher[i].thread_id, NULL) != 0)
44
{
45
free(data);
46
return (0);
47
}
48
i++;
49
}
50
return (1);
51
}
52
53
int ft_create_philosophers(t_data *data)
54
{
55
int i;
56
57
i = 0;
58
data->birth = ft_timestamp();
59
while (i < data->philos_num)
60
{
61
data->philosopher[i].last_meal = ft_timestamp();
62
data->n = &data->philosopher[i];
63
if (pthread_create(&data->n->thread_id, NULL, &routine, data->n) != 0)
64
{
65
free(data);
66
return (0);
67
}
68
usleep(100);
69
i++;
70
}
71
if (!ft_join_destroy(data))
72
return (0);
73
return (1);
74
}
75
76