Malloy
Loading...
Searching...
No Matches
action_queue.hpp
1#pragma once
2
3#include <boost/asio/io_context.hpp>
4#include <boost/asio/strand.hpp>
5
6#include <queue>
7
8namespace malloy::detail
9{
10
21 template<typename Executor>
23 {
24 using act_t = std::function<void(const std::function<void()>&)>;
25 using acts_t = std::queue<act_t>;
26 using ioc_t = boost::asio::strand<Executor>;
27
28 public:
34 explicit
35 action_queue(ioc_t ioc) :
36 m_ioc{std::move(ioc)}
37 {
38 }
39
47 void
48 push(act_t act)
49 {
50 boost::asio::dispatch(m_ioc, [this, act = std::move(act)]() mutable -> void {
51 m_acts.push(std::move(act));
52 if (!m_currently_running_act) {
53 run();
54 }
55 });
56 }
57
63 void
65 {
66 m_running = true;
67 exe_next();
68 }
69
70 private:
71 void
72 exe_next()
73 {
74 // Running now...
75 m_currently_running_act = true;
76
77 // Execute
78 boost::asio::dispatch(m_ioc, [this] {
79 if (!m_acts.empty()) {
80 auto act = std::move(m_acts.front());
81 m_acts.pop();
82 std::invoke(std::move(act), [this] {
83 if (!m_acts.empty())
84 exe_next();
85 else
86 m_currently_running_act = false;
87 });
88 }
89
90 // Nothing left to do...
91 else
92 m_currently_running_act = false;
93 });
94 }
95
96 acts_t m_acts;
97 ioc_t m_ioc;
98 std::atomic_bool m_running{false};
99 std::atomic_bool m_currently_running_act{false};
100 };
101
102} // namespace malloy::detail
Stores and executes functions.
Definition: action_queue.hpp:23
void push(act_t act)
Add an action to the queue.
Definition: action_queue.hpp:48
action_queue(ioc_t ioc)
Construct the action queue. It will not execute anything until run() is called.
Definition: action_queue.hpp:35
void run()
Starts the queue running, if it isn't already.
Definition: action_queue.hpp:64