-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularPriorityQueue.hpp
More file actions
116 lines (94 loc) · 2.52 KB
/
CircularPriorityQueue.hpp
File metadata and controls
116 lines (94 loc) · 2.52 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
//
// Created by komdosh on 05.04.2020.
//
#ifndef CIRCULARPRIORITYQUEUE_CIRCULARPRIORITYQUEUE_HPP
#define CIRCULARPRIORITYQUEUE_CIRCULARPRIORITYQUEUE_HPP
#include "boost/heap/priority_queue.hpp"
#include <mutex>
#include <iostream>
#include <thread>
#include <atomic>
#include "Node.hpp"
#define CPQ_NULL INT32_MIN
template<typename T>
class CircularPriorityQueue {
Node<T> *head = nullptr;
Node<T> *getPrevPriorNode() {
Node<T> *node = head->next;
if (node->isHead) {
return node;
}
Node<T> *prevNode = head->next;
Node<T> *prevPriorNode = prevNode;
T priorValue = prevNode->top();
do {
T value = node->top();
if (priorValue == CPQ_NULL || (value != CPQ_NULL && priorValue < value)) {
priorValue = value;
prevPriorNode = prevNode;
}
node = node->next;
prevNode = node;
} while (!node->isHead);
return prevPriorNode;
}
public:
CircularPriorityQueue() {
this->head = new Node<T>(true);
}
void push(T el) {
Node<T> *node = head;
do {
if (node->usedMutex.try_lock()) {
node->pushAndUnlock(el);
return;
}
node = node->next;
} while (!node->isHead);
node = node->createNewNext();
node->pushAndUnlock(el);
}
void pop() {
Node<T> *prev = getPrevPriorNode();
Node<T> *nodeToPop = prev->next;
nodeToPop->usedMutex.lock();
bool needToDelete = nodeToPop->pop();
if (needToDelete && prev->next != nodeToPop->next) {
prev->next = nodeToPop->next;
}
nodeToPop->usedMutex.unlock();
}
T top() {
Node<T> *prev = getPrevPriorNode();
return prev->next->top();
}
bool isEmpty() {
Node<T> *node = head;
do {
if (!node->isEmpty()) {
return false;
}
node = node->next;
} while (node != head);
return true;
}
int size() {
int size = 0;
Node<T> *node = head;
do {
size += node->size();
node = node->next;
} while (node != head);
return size;
}
int nodes() {
int size = 0;
Node<T> *node = head;
do {
++size;
node = node->next;
} while (node != head);
return size;
}
};
#endif //CIRCULARPRIORITYQUEUE_CIRCULARPRIORITYQUEUE_HPP