-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.hpp
More file actions
84 lines (65 loc) · 1.37 KB
/
queue.hpp
File metadata and controls
84 lines (65 loc) · 1.37 KB
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
#ifndef _queue_hpp_
#define _queue_hpp_
#include <atomic>
#include <condition_variable>
#include <deque>
#include <mutex>
template <typename T, typename Container = std::deque<T>>
class queue
{
public:
queue() : m_disabled(false) {}
~queue()
{
disable();
}
bool put(const T & obj)
{
if (disabled())
{
return false;
}
std::unique_lock<std::mutex> lock(m_mutex);
m_queue.emplace_back(obj);
m_cond.notify_one();
return true;
}
bool get(T & obj)
{
if (disabled())
{
return false;
}
std::unique_lock<std::mutex> lock(m_mutex);
while (m_queue.empty())
{
if (disabled())
{
return false;
}
m_cond.wait(lock);
if (disabled())
{
return false;
}
}
obj = m_queue.front();
m_queue.pop_front();
return true;
}
void disable()
{
m_disabled.store(true, std::memory_order_relaxed);
m_cond.notify_all();
}
bool disabled() const
{
return m_disabled.load(std::memory_order_relaxed);
}
private:
std::mutex m_mutex;
std::condition_variable m_cond;
Container m_queue;
std::atomic_bool m_disabled;
};
#endif // _queue_hpp_