-
Notifications
You must be signed in to change notification settings - Fork 1
/
queue.h
73 lines (61 loc) · 1.44 KB
/
queue.h
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
#ifndef JOB_SCHEDULER__QUEUE_H_
#define JOB_SCHEDULER__QUEUE_H_
#include <cstddef>
#include <pthread.h>
#include <utility>
#include <stdexcept>
template<typename T>
struct Queue {
Queue(size_t capacity);
T &pop();
void push(const T &value);
void push(T &&value);
[[gnu::always_inline]]
inline bool emtpy();
[[gnu::always_inline]]
inline bool full();
private:
T *data;
size_t capacity;
size_t left;
size_t right;
};
template<typename T>
Queue<T>::Queue(size_t capacity)
: capacity{capacity}, left{0U}, right{0U}, data{new T[capacity]} {}
template<typename T>
T &Queue<T>::pop() {
if (emtpy()) {
throw std::runtime_error("Cannot pop from empty queue");
}
T &elem = data[left++];
left = (left != capacity) ? left : 0U;
return elem;
}
template<typename T>
void Queue<T>::push(const T &value) {
if (full()) {
throw std::runtime_error("Cannot push to a full queue");
}
data[right++] = value;
right = (right != capacity) ? right : 0U;
}
template<typename T>
void Queue<T>::push(T &&value) {
if (full()) {
throw std::runtime_error("Cannot push to a full queue");
}
data[right++] = std::move(value);
right = (right != capacity) ? right : 0U;
}
template<typename T>
bool Queue<T>::emtpy() {
bool res = left == right;
return res;
}
template<typename T>
bool Queue<T>::full() {
bool res = ((left == right + 1) || (right == capacity && left == 0));
return res;
}
#endif //JOB_SCHEDULER__QUEUE_H_