-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.c
More file actions
104 lines (95 loc) · 2.76 KB
/
init.c
File metadata and controls
104 lines (95 loc) · 2.76 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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* init.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: syanak <syanak@student.42kocaeli.com.tr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/08/25 10:13:23 by syanak #+# #+# */
/* Updated: 2025/08/25 18:00:10 by syanak ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosophers.h"
#include <stdlib.h>
t_data *init_data(int argc, char **argv)
{
t_data *data;
data = malloc(sizeof(t_data));
if (!data)
return (NULL);
data->num_philos = ft_atoi(argv[1]);
data->time_to_die = ft_atoi(argv[2]);
data->time_to_eat = ft_atoi(argv[3]);
data->time_to_sleep = ft_atoi(argv[4]);
if (argc == 6)
data->must_eat_count = ft_atoi(argv[5]);
else
data->must_eat_count = -1;
data->stop_simulation = 0;
data->all_ate_enough = 0;
data->start_flag = 0;
data->start_time = get_time();
data->end_time = 0;
pthread_mutex_init(&data->print_mutex, NULL);
pthread_mutex_init(&data->death_mutex, NULL);
pthread_mutex_init(&data->meal_mutex, NULL);
pthread_mutex_init(&data->start_mutex, NULL);
return (data);
}
t_philo *create_philo(int id, t_data *data)
{
t_philo *new;
new = malloc(sizeof(t_philo));
if (!new)
return (NULL);
new->id = id;
new->meals_eaten = 0;
new->last_meal_time = data->start_time;
new->next = NULL;
new->prev = NULL;
new->right_fork = malloc(sizeof(pthread_mutex_t) * 1);
if (!new->right_fork)
return (NULL);
pthread_mutex_init(new->right_fork, NULL);
new->data = data;
return (new);
}
void set_left_forks(t_philo *head)
{
t_philo *current;
int i;
i = 0;
current = head;
while (i < head->data->num_philos)
{
current->left_fork = current->prev->right_fork;
current = current->next;
i++;
}
}
t_philo *init_philosophers(t_data *data)
{
t_philo *head;
t_philo *current;
t_philo *new;
int i;
head = create_philo(1, data);
if (!head)
return (NULL);
current = head;
i = 2;
while (i <= data->num_philos)
{
new = create_philo(i, data);
if (!new)
return (NULL);
current->next = new;
new->prev = current;
current = new;
i++;
}
current->next = head;
head->prev = current;
set_left_forks(head);
return (head);
}