Wire Sysio Wire Sysion 1.0.0
Loading...
Searching...
No Matches
thread_utils.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <boost/asio/io_context.hpp>
4#include <boost/asio/thread_pool.hpp>
5#include <boost/asio/post.hpp>
6#include <future>
7#include <memory>
8#include <optional>
9
10namespace sysio { namespace chain {
11
17 public:
18 // name_prefix is name appended with -## of thread.
19 // short name_prefix (6 chars or under) is recommended as console_appender uses 9 chars for thread name
20 named_thread_pool( std::string name_prefix, size_t num_threads );
21
22 // calls stop()
24
25 boost::asio::io_context& get_executor() { return _ioc; }
26
27 // destroy work guard, stop io_context, join thread_pool, and stop thread_pool
28 void stop();
29
30 private:
31 using ioc_work_t = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>;
32
33 boost::asio::thread_pool _thread_pool;
34 boost::asio::io_context _ioc;
35 std::optional<ioc_work_t> _ioc_work;
36 };
37
38
39 // async on thread_pool and return future
40 template<typename F>
41 auto async_thread_pool( boost::asio::io_context& thread_pool, F&& f ) {
42 auto task = std::make_shared<std::packaged_task<decltype( f() )()>>( std::forward<F>( f ) );
43 boost::asio::post( thread_pool, [task]() { (*task)(); } );
44 return task->get_future();
45 }
46
47} } // sysio::chain
48
49
named_thread_pool(std::string name_prefix, size_t num_threads)
boost::asio::io_context & get_executor()
auto async_thread_pool(boost::asio::io_context &thread_pool, F &&f)