async_mqtt 4.1.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 template <typename CompletionToken>
34 void post(CompletionToken&& token) {
35 as::post(
36 queue_,
37 std::forward<CompletionToken>(token)
38 );
39 if (!working_ && queue_.stopped()) {
40 queue_.restart();
41 queue_.poll_one();
42 }
43 }
44
45 bool stopped() const {
46 return queue_.stopped();
47 }
48
49 std::size_t poll_one() {
50 working_ = false;
51 if (queue_.stopped()) queue_.restart();
52 return queue_.poll_one();
53 }
54
55 std::size_t poll() {
56 working_ = false;
57 if (queue_.stopped()) queue_.restart();
58 return queue_.poll();
59 }
60
61private:
62 as::io_context queue_;
63 bool working_ = false;
64 optional<as::executor_work_guard<as::io_context::executor_type>> guard_;
65};
66
67} // namespace async_mqtt
68
69#endif // ASYNC_MQTT_UTIL_IOC_QUEUE_HPP