CppCommon
1.0.5.0
C++ Common Library
Loading...
Searching...
No Matches
include
threads
mpsc_linked_batcher.inl
Go to the documentation of this file.
1
9
namespace
CppCommon
{
10
11
template
<
typename
T>
12
inline
MPSCLinkedBatcher<T>::MPSCLinkedBatcher
() : _head(nullptr)
13
{
14
}
15
16
template
<
typename
T>
17
inline
MPSCLinkedBatcher<T>::~MPSCLinkedBatcher
()
18
{
19
// Remove all nodes from the linked batcher
20
Dequeue([](
const
T&){});
21
}
22
23
template
<
typename
T>
24
inline
bool
MPSCLinkedBatcher<T>::Enqueue
(
const
T& item)
25
{
26
T temp = item;
27
return
Enqueue(std::forward<T>(temp));
28
}
29
30
template
<
typename
T>
31
inline
bool
MPSCLinkedBatcher<T>::Enqueue
(T&& item)
32
{
33
// Create new head node
34
Node* node =
new
Node;
35
if
(node ==
nullptr
)
36
return
false
;
37
38
// Fill new head node with the given value
39
node->value = std::move(item);
40
41
// Insert new head node into the batcher and linked it with the previous one
42
Node* prev_head = _head.load(std::memory_order_relaxed);
43
do
44
{
45
node->next = prev_head;
46
}
while
(!_head.compare_exchange_weak(prev_head, node, std::memory_order_release));
47
48
return
true
;
49
}
50
51
template
<
typename
T>
52
inline
bool
MPSCLinkedBatcher<T>::Dequeue
(
const
std::function<
void
(
const
T&)>& handler)
53
{
54
assert((handler) &&
"Batch handler must be valid!"
);
55
56
Node* last = _head.exchange(
nullptr
, std::memory_order_acq_rel);
57
Node* first =
nullptr
;
58
59
// Check if the linked batcher is empty
60
if
(last ==
nullptr
)
61
return
false
;
62
63
// Reverse the order to get nodes in FIFO order
64
do
65
{
66
Node* temp = last;
67
last = last->next;
68
temp->next = first;
69
first = temp;
70
}
while
(last !=
nullptr
);
71
72
// Process all items in a batch mode
73
do
74
{
75
Node* temp = first;
76
first = first->next;
77
// Process the item with the given handler
78
handler(temp->value);
79
delete
temp;
80
}
while
(first !=
nullptr
);
81
82
return
true
;
83
}
84
85
}
// namespace CppCommon
CppCommon::MPSCLinkedBatcher::~MPSCLinkedBatcher
~MPSCLinkedBatcher()
Definition
mpsc_linked_batcher.inl:17
CppCommon::MPSCLinkedBatcher::Dequeue
bool Dequeue(const std::function< void(const T &)> &handler=[](const int &){})
Dequeue all items from the linked queue (single consumer thread method)
Definition
mpsc_linked_batcher.inl:52
CppCommon::MPSCLinkedBatcher::Enqueue
bool Enqueue(const T &item)
Enqueue an item into the linked batcher (multiple producers threads method)
Definition
mpsc_linked_batcher.inl:24
CppCommon::MPSCLinkedBatcher::MPSCLinkedBatcher
MPSCLinkedBatcher()
Definition
mpsc_linked_batcher.inl:12
CppCommon
C++ Common project definitions.
Definition
token_bucket.h:15
Generated by
1.9.8