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
|
#include "codexion.h"
# include <stdlib.h> // for atoi(), malloc()
void *routine(void *arg)
{
t_philo *philo;
int number_of_eat_required;
philo = (t_philo *)arg;
if (philo->sim->number_of_philos == 1)
{
print_log(philo, "has taken a fork", 0);
return (0);
}
(void)pthread_mutex_lock(&philo->sim->mutex_number_of_eat_required);
number_of_eat_required = philo->sim->number_of_eat_required;
(void)pthread_mutex_unlock(&philo->sim->mutex_number_of_eat_required);
while (philo->number_of_eats_done != number_of_eat_required)
{
(void)pthread_mutex_lock(&philo->sim->mutex_number_of_eat_required);
number_of_eat_required = philo->sim->number_of_eat_required;
(void)pthread_mutex_unlock(&philo->sim->mutex_number_of_eat_required);
if (philo_routine(philo, philo->right_fork, philo->left_fork) != 0)
return (NULL);
}
return (0);
}
int create_threads(t_sim *sim)
{
t_philo **philos;
int number_of_philos;
t_philo *philo;
philos = sim->philos;
number_of_philos = sim->number_of_philos;
if (pthread_create(&sim->monitor_thread, NULL, monitoring_routine,
sim) != 0)
{
free_philos(sim);
free(sim);
return (1);
}
while (number_of_philos-- > 0)
{
philo = *philos++;
if (pthread_create(&philo->thread_id, NULL, routine, philo) != 0)
{
free_philos(sim);
free(sim);
return (1);
}
}
return (0);
}
int join_threads(t_sim *sim)
{
t_philo **philos;
t_philo *philo;
int threads;
philos = sim->philos;
threads = sim->number_of_philos;
while (threads-- > 0)
{
philo = *philos++;
if (pthread_join(philo->thread_id, NULL) != 0)
{
free_philos(sim);
free_forks(sim);
free(sim);
return (1);
}
}
if (pthread_join(sim->monitor_thread, NULL) != 0)
{
free_philos(sim);
free_forks(sim);
free(sim);
return (1);
}
return (0);
}
int run_threads(t_sim *sim)
{
if (create_threads(sim) != 0)
return (1);
if (join_threads(sim) != 0)
return (1);
return (0);
}
|