-
Notifications
You must be signed in to change notification settings - Fork 0
/
SynchronizedQueue.h
75 lines (65 loc) · 1.46 KB
/
SynchronizedQueue.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
74
75
#pragma once
#include <mutex>
#include <condition_variable>
#include <queue>
#include <optional>
namespace stdx
{
template<typename T, class Container = std::queue<T>>
class SynchronizedQueue
{
public:
SynchronizedQueue() : stopFlag(false) {}
template<class U=T>
std::optional<T> push(U &&t)
{
std::unique_lock<std::mutex> lock(mutex);
if (!stopFlag)
{
queue.push(std::forward<U>(t));
lock.unlock();
conditionVariable.notify_one();
return std::nullopt;
}
return std::forward<U>(t);
}
std::optional<T> pop()
{
std::unique_lock<std::mutex> lock(mutex);
while (queue.empty() && !stopFlag)
{
conditionVariable.wait(lock);
}
if (!queue.empty())
{
T t = std::move(queue.front());
queue.pop();
return std::move(t);
}
return {};
}
void stop()
{
{
std::unique_lock<std::mutex> lock(mutex);
stopFlag = true;
}
conditionVariable.notify_all();
}
size_t size() const
{
std::lock_guard<std::mutex> lock(mutex);
return queue.size();
}
bool empty() const
{
std::lock_guard<std::mutex> lock(mutex);
return queue.empty();
}
private:
Container queue;
mutable std::mutex mutex;
std::condition_variable conditionVariable;
bool stopFlag;
};
}