Repository navigation
Expand file tree
/
Copy pathphilo.c
More file actions
105 lines (95 loc) · 2.7 KB
/
Copy pathphilo.c
File metadata and controls
105 lines (95 loc) · 2.7 KB
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* philo.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ebakirog <ebakirog@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/02/07 22:40:51 by ebakirog #+# #+# */
/* Updated: 2024/02/07 23:22:38 by ebakirog ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
#include <stdlib.h>
#include <stdio.h>
void *life_loop(void *arg)
{
while (1)
{
is_eating(arg);
is_sleeping(arg);
is_thinking(arg);
}
return (NULL);
}
int create_join(t_table *tab)
{
int i;
i = -1;
while (++i < tab->p_count)
{
if (pthread_join(tab->philo[i].thread, NULL) != 0)
return (error_msg("Thread Join"), -1);
}
return (0);
}
void create_fork(t_table *tab)
{
int i;
int x;
i = -1;
while (++i < tab->p_count)
{
tab->philo[i].self_fork = true;
x = ((i - 1) + tab->p_count) % tab->p_count;
tab->philo[i].other_fork = &tab->philo[x].self_fork;
}
}
int create_philo(t_table *tab)
{
int i;
int tmp;
i = -1;
tab->philo = (t_philo *)malloc(sizeof(t_philo) * tab->p_count);
if (tab->philo == NULL)
return (error_msg("Malloc Error"), -1);
while (++i < tab->p_count)
tab->philo[i].table = tab;
i = -1;
while (++i < tab->p_count)
{
tab->philo[i].id = i + 1;
tab->philo[i].self_fork = true;
tmp = ((i - 1) + tab->p_count) % tab->p_count;
tab->philo[i].other_fork = &tab->philo[tmp].self_fork;
if (pthread_create(&tab->philo[i].thread, NULL, &life_loop,
&tab->philo[i]) != 0)
return (error_msg("Thread Create"), -1);
}
create_fork(tab);
if (create_join(tab) == -1)
return (-1);
return (0);
}
int main(int ac, char **av)
{
t_table tab;
if (ac == 5 || ac == 6)
{
av++;
if (check_all(av, ac - 1) == -1)
return (error_msg("Wrong Argument"), 1);
tab.start = get_time();
if (tab.start == -1)
return (1);
assign_arg(av, ac - 1, &tab);
if (create_philo(&tab) == -1)
return (free(tab.philo), 1);
if (pthread_mutex_init(&tab.mutex, NULL) != 0)
return (error_msg("Mutex İnit"), free(tab.philo), 1);
if (pthread_mutex_destroy(&tab.mutex) != 0)
return (error_msg("Mutex Destroy"), free(tab.philo), 1);
return (0);
}
return (error_msg("Invalid Argument"), 1);
}