async_mqtt 5.0.0
Loading...
Searching...
No Matches
ioc_queue.hpp
1// Copyright Takatoshi Kondo 2023
2//
3// Distributed under the Boost Software License, Version 1.0.
4// (See accompanying file LICENSE_1_0.txt or copy at
5// http://www.boost.org/LICENSE_1_0.txt)
6
7#if !defined(ASYNC_MQTT_UTIL_IOC_QUEUE_HPP)
8#define ASYNC_MQTT_UTIL_IOC_QUEUE_HPP
9
10#include <boost/asio.hpp>
11
12#include <async_mqtt/util/optional.hpp>
13
14namespace async_mqtt {
15
16namespace as = boost::asio;
17
18class ioc_queue {
19public:
20 ioc_queue() {
21 queue_.stop();
22 }
23
24 void start_work() {
25 working_ = true;
26 guard_.emplace(queue_.get_executor());
27 }
28
29 void stop_work() {
30 guard_.reset();
31 }
32
33 bool immediate_executable() const {
34 return !working_ && queue_.stopped();
35 }
36
37 template <typename CompletionToken>
38 void post(CompletionToken&& token) {
39 as::post(
40 queue_,
41 std::forward<CompletionToken>(token)
42 );
43 if (immediate_executable()) {
44 queue_.restart();
45 queue_.poll_one();
46 }
47 }
48
49 bool stopped() const {
50 return queue_.stopped();
51 }
52
53 std::size_t poll_one() {
54 working_ = false;
55 if (queue_.stopped()) queue_.restart();
56 return queue_.poll_one();
57 }
58
59 std::size_t poll() {
60 working_ = false;
61 if (queue_.stopped()) queue_.restart();
62 return queue_.poll();
63 }
64
65private:
66 as::io_context queue_{BOOST_ASIO_CONCURRENCY_HINT_UNSAFE};
67 bool working_ = false;
68 optional<as::executor_work_guard<as::io_context::executor_type>> guard_;
69};
70
71} // namespace async_mqtt
72
73#endif // ASYNC_MQTT_UTIL_IOC_QUEUE_HPP