summaryrefslogtreecommitdiff
path: root/src/queue.c
blob: 76907d95d8c620c0bae8d2cfe3e890bb279648de (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
#include "codexion.h"
# include <stdlib.h>   // for atoi(), malloc()
# include <stdio.h>    // for printf()

void	heapify(t_fork *fork)
{
	t_ticket	t1;
	t_ticket	t2;	

	(void)pthread_mutex_lock(&fork->mutex_pq);
	if (fork->pq.size < 2)
	{
		(void)pthread_mutex_unlock(&fork->mutex_pq);
		return ;
	}
	(void)pthread_mutex_unlock(&fork->mutex_pq);
	t1 = fork->pq.items[0];
	t2 = fork->pq.items[1];
	if (t1.num > t2.num)
		swap(t1, t2);
}

void	enqueue(t_fork *fork, t_ticket ticket)
{
	int	queue_size;

	(void)pthread_mutex_lock(&fork->mutex_pq);
	queue_size = fork->pq.size; 
	(void)pthread_mutex_unlock(&fork->mutex_pq);
	if (queue_size == MAX) 
	{
		printf("Priority queue is full\n");
		return ;
	}
	(void)pthread_mutex_lock(&fork->mutex_pq);
	fork->pq.items[fork->pq.size++] = ticket;
	(void)pthread_mutex_unlock(&fork->mutex_pq);
}

void	dequeue(t_fork *fork)
{
	int	queue_size;

	(void)pthread_mutex_lock(&fork->mutex_pq);
	queue_size = fork->pq.size; 
	(void)pthread_mutex_unlock(&fork->mutex_pq);
	if (!queue_size) 
	{
		printf("Priority queue is empty\n");
		return ;
	}
	(void)pthread_mutex_lock(&fork->mutex_pq);
	fork->pq.items[0] = fork->pq.items[--fork->pq.size];
	(void)pthread_mutex_unlock(&fork->mutex_pq);
}