CppCommon 1.0.5.0
C++ Common Library
Loading...
Searching...
No Matches
wait_queue.inl
Go to the documentation of this file.
1
9namespace CppCommon {
10
11template<typename T>
12inline WaitQueue<T>::WaitQueue(size_t capacity) : _closed(false), _capacity(capacity)
13{
14}
15
16template<typename T>
18{
19 Close();
20}
21
22template<typename T>
23inline bool WaitQueue<T>::closed() const
24{
25 Locker<CriticalSection> locker(_cs);
26 return _closed;
27}
28
29template<typename T>
30inline size_t WaitQueue<T>::capacity() const
31{
32 if (_capacity > 0)
33 return _capacity;
34
35 Locker<CriticalSection> locker(_cs);
36 return _queue.size();
37}
38
39template<typename T>
40inline size_t WaitQueue<T>::size() const
41{
42 Locker<CriticalSection> locker(_cs);
43 return _queue.size();
44}
45
46template<typename T>
47inline bool WaitQueue<T>::Enqueue(const T& item)
48{
49 Locker<CriticalSection> locker(_cs);
50
51 if (_closed)
52 return false;
53
54 do
55 {
56 if ((_capacity == 0) || (_queue.size() < _capacity))
57 {
58 _queue.push(item);
59 _cv1.NotifyOne();
60 return true;
61 }
62
63 _cv2.Wait(_cs, [this]() { return (_closed || (_capacity == 0) || (_queue.size() < _capacity)); });
64
65 } while (!_closed);
66
67 return false;
68}
69
70template<typename T>
71inline bool WaitQueue<T>::Enqueue(T&& item)
72{
73 Locker<CriticalSection> locker(_cs);
74
75 if (_closed)
76 return false;
77
78 do
79 {
80 if ((_capacity == 0) || (_queue.size() < _capacity))
81 {
82 _queue.emplace(item);
83 _cv1.NotifyOne();
84 return true;
85 }
86
87 _cv2.Wait(_cs, [this]() { return (_closed || (_capacity == 0) || (_queue.size() < _capacity)); });
88
89 } while (!_closed);
90
91 return false;
92}
93
94template<typename T>
95inline bool WaitQueue<T>::Dequeue(T& item)
96{
97 Locker<CriticalSection> locker(_cs);
98
99 if (_closed && _queue.empty())
100 return false;
101
102 do
103 {
104 if (!_queue.empty())
105 {
106 item = _queue.front();
107 _queue.pop();
108 _cv2.NotifyOne();
109 return true;
110 }
111
112 _cv1.Wait(_cs, [this]() { return (_closed || !_queue.empty()); });
113
114 } while (!_closed || !_queue.empty());
115
116 return false;
117}
118
119template<typename T>
121{
122 Locker<CriticalSection> locker(_cs);
123 _closed = true;
124 _cv1.NotifyAll();
125 _cv2.NotifyAll();
126}
127
128} // namespace CppCommon
Locker synchronization primitive.
Definition locker.h:23
bool Enqueue(const T &item)
Enqueue an item into the wait queue.
bool Dequeue(T &item)
Dequeue an item from the wait queue.
void Close()
Close the wait queue.
WaitQueue(size_t capacity=0)
Default class constructor.
size_t capacity() const
Get wait queue capacity.
bool closed() const
Is wait queue closed?
size_t size() const
Get wait queue size.
C++ Common project definitions.