-
Notifications
You must be signed in to change notification settings - Fork 0
/
BlockingQueue.cpp
104 lines (83 loc) · 1.42 KB
/
BlockingQueue.cpp
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
#include <condition_variable>
#include <mutex>
#include <thread>
#include <queue>
template <typename T>
class BlockingQueue
{
std::queue<T> Q;
std::mutex mutex;
std::condition_variable cv;
public:
BlockingQueue() {}
BlockingQueue(BlockingQueue<T>&& other)
{
std::lock_guard lock(mutex);
Q = other.Q;
while (other.Q.size() > 0)
other.Q.clear();
}
BlockingQueue<T>& operator= (BlockingQueue<T>&& other)
{
if (this == &other)
return *this;
std::lock_guard lock(mutex);
Q = other.Q;
while (other.Q.size() > 0)
other.Q.pop();
return *this;
}
BlockingQueue(const BlockingQueue<T>&) = delete;
BlockingQueue<T>& operator= (const BlockingQueue<T>&) = delete;
T deQueue()
{
std::unique_lock lock(mutex);
if (!Q.empty())
{
T temp = Q.front();
Q.pop();
return temp;
}
while (Q.empty())
{
cv.wait(lock, [this]() {return (!Q.empty()); });
T temp = Q.front();
Q.pop();
return temp;
}
}
void enQueue(const T& t)
{
{
std::unique_lock<std::mutex> lock(mutex);
Q.push(t);
}
cv.notify_all();
}
T& front()
{
std::lock_guard lock(mutex);
T temp;
if (!Q.empty())
{
temp = Q.front();
}
else
{
cv.wait(lock, [this]() {return (!Q.empty()); });
temp = Q.front();
}
return temp;
}
void clear()
{
std::lock_guard lock(mutex);
while (!Q.empty())
Q.pop();
}
size_t size()
{
std::lock_guard lock(mutex);
return Q.size();
}
};