-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmang_ate.c
116 lines (106 loc) · 2.94 KB
/
mang_ate.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
112
113
114
115
116
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mang_ate.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: aaljaber <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/04/19 20:41:40 by aaljaber #+# #+# */
/* Updated: 2022/04/19 20:41:42 by aaljaber ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
/* the way to handle the greedy philo */
void init_ate_arr(void *arg)
{
t_main *main;
int i;
main = (t_main *)arg;
i = -1;
while (++i < main->num_philo)
main->ate[i] = -1;
}
int did_eat(void *arg)
{
t_philo *dumb;
dumb = (t_philo *)arg;
pthread_mutex_lock(&dumb->m_info->a_mutex[dumb->left]);
if (dumb->m_info->ate[dumb->left] != dumb->id)
{
dumb->m_info->ate[dumb->left] = dumb->id;
pthread_mutex_unlock(&dumb->m_info->a_mutex[dumb->left]);
}
else
pthread_mutex_unlock(&dumb->m_info->a_mutex[dumb->left]);
pthread_mutex_lock(&dumb->m_info->a_mutex[dumb->right]);
if (dumb->m_info->ate[dumb->right] != dumb->id)
{
dumb->m_info->ate[dumb->right] = dumb->id;
pthread_mutex_unlock(&dumb->m_info->a_mutex[dumb->right]);
}
else
pthread_mutex_unlock(&dumb->m_info->a_mutex[dumb->right]);
return (0);
}
int can_eat(void *arg)
{
t_philo *dumb;
dumb = (t_philo *)arg;
dumb->r = 0;
dumb->l = 0;
pthread_mutex_lock(&dumb->m_info->a_mutex[dumb->left]);
if (dumb->m_info->ate[dumb->left] != dumb->id)
{
pthread_mutex_unlock(&dumb->m_info->a_mutex[dumb->left]);
dumb->l = 1;
}
else
pthread_mutex_unlock(&dumb->m_info->a_mutex[dumb->left]);
pthread_mutex_lock(&dumb->m_info->a_mutex[dumb->right]);
if (dumb->m_info->ate[dumb->right] != dumb->id)
{
pthread_mutex_unlock(&dumb->m_info->a_mutex[dumb->right]);
dumb->r = 1;
}
else
pthread_mutex_unlock(&dumb->m_info->a_mutex[dumb->right]);
if (dumb->r == 1 && dumb->l == 1)
return (1);
return (0);
}
void clear_ate_arr(void *arg)
{
t_philo *dumb;
int i;
dumb = (t_philo *)arg;
i = -1;
pthread_mutex_lock(&dumb->m_info->l_mut);
while (++i < dumb->m_info->num_philo)
{
pthread_mutex_lock(&dumb->m_info->a_mutex[i]);
dumb->m_info->ate[i] = 0;
pthread_mutex_unlock(&dumb->m_info->a_mutex[i]);
}
pthread_mutex_unlock(&dumb->m_info->l_mut);
}
int mang_eat(void *arg, int op)
{
if (op == 0)
{
init_ate_arr(arg);
return (1);
}
else if (op == 1)
{
if (can_eat(arg))
return (1);
else
return (0);
}
else if (op == 2)
{
did_eat(arg);
return (1);
}
return (0);
}