summaryrefslogtreecommitdiff
path: root/src/utils_routine.c
blob: 37e3f3dcc31ac0bd60502a203b3d0d655a47170b (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include "codexion.h"
# include <stdio.h>    // for printf()
# include <unistd.h>   // for usleep()

void	eat(t_philo *philo)
{
	t_sim	*sim;

	(void)pthread_mutex_lock(&philo->mutex_sim);
	sim = philo->sim;
	(void)pthread_mutex_unlock(&philo->mutex_sim);
	(void)pthread_mutex_lock(&philo->mutex_beginning_last_eat_time);
	philo->beginning_last_eat_time = get_rel_time(sim);
	(void)pthread_mutex_unlock(&philo->mutex_beginning_last_eat_time);
	print_log(philo, "is eating", 0);
	usleep(philo->sim->time_to_eat * 1000);
	(void)pthread_mutex_lock(&philo->mutex_number_of_eats_done);
	philo->number_of_eats_done++;
	(void)pthread_mutex_unlock(&philo->mutex_number_of_eats_done);
}

void	reflect_and_think(t_philo *philo)
{
	print_log(philo, "is reflecting", 0);
	usleep(philo->sim->time_to_reflect * 1000);
	print_log(philo, "is thinking", 0);
	usleep(philo->sim->time_to_think * 1000);
}

int	wait_for_fork(t_philo *philo, t_fork *fork)
{
	int		cooldown;
	int		wait;
	int		last_released;
	t_sim	*sim;

	(void)pthread_mutex_lock(&philo->mutex_sim);
	sim = philo->sim;
	(void)pthread_mutex_unlock(&philo->mutex_sim);
	(void)pthread_mutex_lock(&philo->sim->mutex_cooldown);
	cooldown = philo->sim->fork_cooldown;
	(void)pthread_mutex_unlock(&philo->sim->mutex_cooldown);
	(void)pthread_mutex_lock(&fork->mutex_last_released);
	last_released = fork->last_released;
	(void)pthread_mutex_unlock(&fork->mutex_last_released);
	wait = cooldown - (get_rel_time(sim) - last_released);
	return (wait);
}

void	wait_for_longest_cooldown(t_philo *philo, t_fork *f1, t_fork *f2)
{
	int	w1;
	int	w2;
	int	wait;

	wait = 0;
	if (get_id(philo) % 2 != 0 && philo->number_of_eats_done < 1)
		usleep(50);
	w1 = wait_for_fork(philo, f1);
	w2 = wait_for_fork(philo, f2);
	if (w1 >= w2 && w1 > 0)
		wait = w1;
	else if (w2 >= w1 && w2 > 0)
		wait = w2;
	usleep(wait * 1000);
}

void	update_last_released(t_sim *sim, t_fork *f1, t_fork *f2)
{
	int	time_to_eat;

	(void)pthread_mutex_lock(&sim->mutex_time_to_eat);
	time_to_eat = sim->time_to_eat;
	(void)pthread_mutex_unlock(&sim->mutex_time_to_eat);
	(void)pthread_mutex_lock(&f1->mutex_last_released);
	f1->last_released = get_rel_time(sim) + time_to_eat;
	(void)pthread_mutex_unlock(&f1->mutex_last_released);
	(void)pthread_mutex_lock(&f2->mutex_last_released);
	f2->last_released = get_rel_time(sim) + time_to_eat;
	(void)pthread_mutex_unlock(&f2->mutex_last_released);
}