forked from zerotier/ZeroTierOne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBlockingQueue.hpp
132 lines (117 loc) · 2.2 KB
/
BlockingQueue.hpp
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/*
* Copyright (c)2019 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2026-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#ifndef ZT_BLOCKINGQUEUE_HPP
#define ZT_BLOCKINGQUEUE_HPP
#include <queue>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <atomic>
#include <vector>
namespace ZeroTier {
/**
* Simple C++11 thread-safe queue
*
* Do not use in node/ since we have not gone C++11 there yet.
*/
template <class T>
class BlockingQueue
{
public:
BlockingQueue(void) : r(true) {}
inline void post(T t)
{
std::lock_guard<std::mutex> lock(m);
q.push(t);
c.notify_one();
}
inline void postLimit(T t,const unsigned long limit)
{
std::unique_lock<std::mutex> lock(m);
for(;;) {
if (q.size() < limit) {
q.push(t);
c.notify_one();
break;
}
if (!r)
break;
gc.wait(lock);
}
}
inline void stop(void)
{
std::lock_guard<std::mutex> lock(m);
r = false;
c.notify_all();
gc.notify_all();
}
inline bool get(T &value)
{
std::unique_lock<std::mutex> lock(m);
if (!r)
return false;
while (q.empty()) {
c.wait(lock);
if (!r) {
gc.notify_all();
return false;
}
}
value = q.front();
q.pop();
gc.notify_all();
return true;
}
inline std::vector<T> drain()
{
std::vector<T> v;
while (!q.empty()) {
v.push_back(q.front());
q.pop();
}
return v;
}
enum TimedWaitResult
{
OK,
TIMED_OUT,
STOP
};
inline TimedWaitResult get(T &value,const unsigned long ms)
{
const std::chrono::milliseconds ms2{ms};
std::unique_lock<std::mutex> lock(m);
if (!r)
return STOP;
while (q.empty()) {
if (c.wait_for(lock,ms2) == std::cv_status::timeout)
return ((r) ? TIMED_OUT : STOP);
else if (!r)
return STOP;
}
value = q.front();
q.pop();
return OK;
}
inline size_t size() const {
return q.size();
}
private:
std::queue<T> q;
mutable std::mutex m;
mutable std::condition_variable c,gc;
std::atomic_bool r;
};
} // namespace ZeroTier
#endif