summaryrefslogtreecommitdiff
path: root/src/scheduler.c
blob: 76c2f8d074f898fd748de156a20ab7009fb0a2f0 (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
82
83
84
85
86
#include "codexion.h"
# include <unistd.h>   // for usleep()
# include <string.h>   // for strcmp()

static t_ticket	take_ticket(t_philo *philo, t_fork *fork)
{
	t_ticket	my_ticket;
	char		*scheduler;
	t_sim		*sim;

	(void)pthread_mutex_lock(&philo->sim->mutex_scheduler);
	scheduler = philo->sim->scheduler;
	(void)pthread_mutex_unlock(&philo->sim->mutex_scheduler);
	if (strcmp(scheduler, "fifo") == 0)
	{
		(void)pthread_mutex_lock(&fork->mutex_ticket_next);
		my_ticket.num = fork->ticket_next++;
		(void)pthread_mutex_unlock(&fork->mutex_ticket_next);
	}
	if (strcmp(scheduler, "edf") == 0)
	{
		(void)pthread_mutex_lock(&philo->mutex_sim);
		sim = philo->sim;
		(void)pthread_mutex_unlock(&philo->mutex_sim);
		my_ticket.num = get_rel_time(sim) + sim->time_to_starve;
	}
	enqueue(fork, my_ticket);
	heapify(fork);
	return (my_ticket);
}

int	get_first_item_queue(t_fork *fork)
{
	int		first_item;

	(void)pthread_mutex_lock(&fork->mutex_pq);
	first_item = fork->pq.items[0].num;
	(void)pthread_mutex_unlock(&fork->mutex_pq);
	return (first_item);
}

static int	is_ticket_first(t_philo *philo, t_fork *f1, 
							t_fork *f2, t_ticket ticket)
{
	t_sim	*sim;

	(void)pthread_mutex_lock(&philo->mutex_sim);
	sim = philo->sim;
	(void)pthread_mutex_unlock(&philo->mutex_sim);
	wait_for_longest_cooldown(philo, f1, f2);
	(void)pthread_mutex_lock(&f1->mutex_cond);
	while (ticket.num != get_first_item_queue(f1))
	{
		if (check_if_philo_starved(sim))
		{
			(void)pthread_mutex_unlock(&f1->mutex_cond);
			return (1);
		}
		pthread_cond_wait(&f1->cond_signal, &f1->mutex_cond);
		wait_for_longest_cooldown(philo, f1, f2);
	}
	(void)pthread_mutex_unlock(&f1->mutex_cond);
	return (0);
}

int	queue_routine(t_philo *philo, t_fork *f1, t_fork *f2)
{
	t_ticket	t1;
	t_ticket	t2;
	//t_sim		*sim;

	//(void)pthread_mutex_lock(&philo->mutex_sim);
	//sim = philo->sim;
	//(void)pthread_mutex_unlock(&philo->mutex_sim);
	if (get_id(philo) % 2 != 0 && philo->number_of_eats_done < 1)
	{
		usleep(100);
	}
	t1 = take_ticket(philo, f1);
	t2 = take_ticket(philo, f2);
	if (is_ticket_first(philo, f1, f2, t1) == 1)
		return (1);
	if (is_ticket_first(philo, f2, f1, t2) == 1)
		return (1);
	return (0);
}