-
Notifications
You must be signed in to change notification settings - Fork 3
/
queue.h
45 lines (35 loc) · 897 Bytes
/
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
#include <atomic>
#include <mutex>
#include <condition_variable>
template<typename T>
class ConcurrentQueue {
public:
ConcurrentQueue() : nowriter(false) {}
void close() {
std::unique_lock<std::mutex> lock(mutex_);
nowriter = true;
condvar.notify_all();
}
void push(T item) {
std::unique_lock<std::mutex> lock(mutex_);
q.push_back(std::move(item));
lock.unlock();
condvar.notify_one();
}
bool pop(T *item) noexcept {
std::unique_lock<std::mutex> lock(mutex_);
while (q.empty() && !nowriter)
condvar.wait(lock);
// Writer signaled end already
if (nowriter)
return false;
*item = std::move(q.front());
q.pop_front();
return true;
}
private:
std::list<T> q; // list of items
std::mutex mutex_; // protection mutex
std::condition_variable condvar; // Wait variable
std::atomic<bool> nowriter; // Indicates no more writes will happen
};