-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQueue.h
62 lines (52 loc) · 1.34 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
#pragma once
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <queue>
template<typename T>
class Queue {
public:
Queue() : interrupt_{false} {}
void push(T item) {
{
std::lock_guard<std::mutex> lock(lock_);
queue_.push(std::move(item));
}
cond_.notify_one();
}
T pop() {
static auto int_return = T{};
std::unique_lock<std::mutex> lock{lock_};
cond_.wait(lock, [&](){return !queue_.empty() || interrupt_;});
if (interrupt_) {
return std::move(int_return);
}
T item = std::move(queue_.front());
queue_.pop();
return item;
}
const T& peek() {
static auto int_return = T{};
std::unique_lock<std::mutex> lock{lock_};
cond_.wait(lock, [&](){return !queue_.empty() || interrupt_;});
if (interrupt_) {
return std::move(int_return);
}
return queue_.front();
}
bool empty() const {
return queue_.empty();
}
typename std::queue<T>::size_type size() const {
return queue_.size();
}
void cancel_pops() {
interrupt_ = true;
cond_.notify_all();
}
private:
std::queue<T> queue_;
std::mutex lock_;
std::condition_variable cond_;
std::atomic<bool> interrupt_;
};