-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads.c
More file actions
98 lines (87 loc) · 2.48 KB
/
threads.c
File metadata and controls
98 lines (87 loc) · 2.48 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* threads.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: syanak <syanak@student.42kocaeli.com.tr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/08/27 12:41:20 by syanak #+# #+# */
/* Updated: 2025/08/29 17:31:40 by syanak ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosophers.h"
int should_stop_simulation(t_philo *philo)
{
int stop;
pthread_mutex_lock(&philo->data->death_mutex);
stop = philo->data->stop_simulation;
pthread_mutex_unlock(&philo->data->death_mutex);
return (stop);
}
void *philosopher_routine(void *arg)
{
t_philo *philo;
philo = (t_philo *)arg;
wait_for_all(philo);
pthread_mutex_lock(&philo->data->meal_mutex);
philo->last_meal_time = get_time();
pthread_mutex_unlock(&philo->data->meal_mutex);
if (philo->id % 2 == 0)
ft_usleep(philo->data->time_to_eat);
while (1)
{
if (should_stop_simulation(philo))
break ;
eat_action(philo);
if (should_stop_simulation(philo))
break ;
sleep_action(philo);
if (should_stop_simulation(philo))
break ;
think_action(philo);
}
return (NULL);
}
int run_simulation(t_philo *first)
{
pthread_t monitor;
if (!start_threads(first))
return (0);
if (pthread_create(&monitor, NULL, monitor_routine, first))
return (0);
pthread_mutex_lock(&first->data->start_mutex);
first->data->start_flag = 1;
pthread_mutex_unlock(&first->data->start_mutex);
pthread_join(monitor, NULL);
join_threads(first);
return (1);
}
int start_threads(t_philo *first)
{
t_philo *current;
int i;
current = first;
i = 0;
while (i < first->data->num_philos)
{
if (pthread_create(¤t->thread, NULL, philosopher_routine,
current))
return (0);
current = current->next;
i++;
}
return (1);
}
void join_threads(t_philo *first)
{
t_philo *current;
int i;
current = first;
i = 0;
while (i < first->data->num_philos)
{
pthread_join(current->thread, NULL);
current = current->next;
i++;
}
}