-
Notifications
You must be signed in to change notification settings - Fork 0
/
working.c
61 lines (57 loc) · 2.24 KB
/
working.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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* working.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: amaach <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/11/05 11:53:15 by amaach #+# #+# */
/* Updated: 2021/11/05 12:02:21 by amaach ### ########.fr */
/* */
/* ************************************************************************** */
#include "philo.h"
t_infos *eating(t_infos *info, int id)
{
pthread_mutex_lock(&info->forks[id]);
pthread_mutex_lock(&info->prints);
printf("%lld %d has taken a fork\n", ft_gettime(), id);
pthread_mutex_unlock(&info->prints);
pthread_mutex_lock(&info->forks[(id + 1) % info->number]);
pthread_mutex_lock(&info->prints);
printf("%lld %d has taken a fork\n", ft_gettime(), id);
pthread_mutex_unlock(&info->prints);
pthread_mutex_lock(&info->is_eating[id]);
info->philo[id].last_eat = ft_gettime();
info->philo[id].eating = 1;
info->philo[id].nb_meals++;
pthread_mutex_lock(&info->prints);
printf("%lld %d is eating\n", ft_gettime(), id);
pthread_mutex_unlock(&info->prints);
my_sleep(info->eat);
info->philo[id].eating = 0;
pthread_mutex_unlock(&info->is_eating[id]);
pthread_mutex_unlock(&info->forks[id]);
pthread_mutex_unlock(&info->forks[(id + 1) % info->number]);
return (info);
}
void *routine(void *arg)
{
int id;
t_infos *info;
id = *(int *)arg;
info = statlist();
info->philo[id].nb_meals = 0;
info->philo[id].eating = 0;
while (1)
{
info = eating(info, id);
pthread_mutex_lock(&info->prints);
printf("%lld %d is sleeping\n", ft_gettime(), id);
pthread_mutex_unlock(&info->prints);
my_sleep(info->sleep);
pthread_mutex_lock(&info->prints);
printf("%lld %d is thinking\n", ft_gettime(), id);
pthread_mutex_unlock(&info->prints);
}
return (0);
}