blob: 065c7c692e3b8ee302e91a66610ff931f9979ab0 (
plain)
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
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* forks.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cacharle <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/02/09 23:46:40 by cacharle #+# #+# */
/* Updated: 2020/04/22 13:26:58 by charles ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo_one.h"
pthread_mutex_t *forks_new(int num)
{
int i;
pthread_mutex_t *forks;
if ((forks = (pthread_mutex_t*)malloc(
sizeof(pthread_mutex_t) * num)) == NULL)
return (NULL);
i = -1;
while (++i < num)
{
if (pthread_mutex_init(&forks[i], NULL) != 0)
{
forks_destroy(forks, i + 1);
return (NULL);
}
}
return (forks);
}
void forks_destroy(pthread_mutex_t *forks, int num)
{
while (num-- > 0)
pthread_mutex_destroy(&forks[num]);
free(forks);
}
t_routine_arg *forks_dispatch(
t_philo *philos,
pthread_mutex_t *forks,
t_philo_conf *conf)
{
int i;
t_routine_arg *routine_args;
if ((routine_args = (t_routine_arg*)malloc(
sizeof(t_routine_arg) * conf->philo_num)) == NULL)
return (NULL);
i = -1;
while (++i < conf->philo_num)
{
routine_args[i].conf = conf;
routine_args[i].philo = philos + i;
routine_args[i].fork_left = forks + i % conf->philo_num;
routine_args[i].fork_right = forks + (i + 1) % conf->philo_num;
}
return (routine_args);
}
|