CppCommon 1.0.5.0
C++ Common Library
Loading...
Searching...
No Matches
mpsc_linked_batcher.inl
Go to the documentation of this file.
1
9namespace CppCommon {
10
11template<typename T>
13{
14}
15
16template<typename T>
18{
19 // Remove all nodes from the linked batcher
20 Dequeue([](const T&){});
21}
22
23template<typename T>
24inline bool MPSCLinkedBatcher<T>::Enqueue(const T& item)
25{
26 T temp = item;
27 return Enqueue(std::forward<T>(temp));
28}
29
30template<typename T>
31inline 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
51template<typename T>
52inline 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
bool Dequeue(const std::function< void(const T &)> &handler=[](const int &){})
Dequeue all items from the linked queue (single consumer thread method)
bool Enqueue(const T &item)
Enqueue an item into the linked batcher (multiple producers threads method)
C++ Common project definitions.