-
Notifications
You must be signed in to change notification settings - Fork 0
/
init_func.c
63 lines (56 loc) · 1.2 KB
/
init_func.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
#include "philo.h"
#include <pthread.h>
#include <stdlib.h>
static void destroy_mutex(int i, t_param *param)
{
int start;
start = 0;
while (start <= i)
{
pthread_mutex_destroy(¶m->forks[start]);
++start;
}
free(param->forks);
}
static int init_philo(t_param *param)
{
int i;
param->philo = malloc(sizeof(t_philo) * param->rule->num_of_philo);
if (!param->philo)
return (FAIL);
i = 0;
while (i < param->rule->num_of_philo)
{
param->philo[i].param = param;
param->philo[i].life = ALIVE;
param->philo[i].eat_count = 0;
param->philo[i].starving_time = 0;
param->philo[i].left_fork = ¶m->forks[i];
param->philo[i].right_fork = ¶m->forks[(i + 1) % param->rule->num_of_philo];
++i;
}
return (SUCCESS);
}
int init_param(t_param *param, t_rule *rule)
{
int i;
param->rule = rule;
param->forks = malloc(sizeof(pthread_mutex_t) * rule->num_of_philo);
if (!param->forks)
return (FAIL);
i = 0;
while (i < rule->num_of_philo)
{
if (pthread_mutex_init(¶m->forks[i], NULL))
{
destroy_mutex(i, param);
return (FAIL);
}
++i;
}
param->tids = malloc(sizeof(pthread_t) * rule->num_of_philo);
if (!param->tids)
return (FAIL);
init_philo(param);
return (SUCCESS);
}