TARAXA
Loading...
Searching...
No Matches
thread_pool.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <boost/asio.hpp>
4
5namespace taraxa::util {
6
7class ThreadPool : std::enable_shared_from_this<ThreadPool> {
8 using asio_callback = std::function<void(boost::system::error_code const &)>;
9
10 boost::asio::io_context ioc_;
11 boost::asio::executor_work_guard<decltype(ioc_)::executor_type> ioc_work_;
12 std::vector<std::thread> threads_;
13
14 std::atomic<uint64_t> num_pending_tasks_ = 0;
15
16 public:
17 explicit ThreadPool(size_t num_threads = std::thread::hardware_concurrency(), bool _start = true);
19
20 ThreadPool(ThreadPool const &) = delete;
21 ThreadPool &operator=(ThreadPool const &) = delete;
22 ThreadPool(ThreadPool &&) = delete;
24
25 auto capacity() const { return threads_.capacity(); }
26 uint64_t num_pending_tasks() const { return num_pending_tasks_; }
27
28 // TODO eliminate
29 auto &unsafe_get_io_context() { return ioc_; }
30
31 void start();
32 bool is_running() const;
33 void stop();
34
35 std::future<void> post(uint64_t do_in_ms, asio_callback action);
36 std::future<void> post(uint64_t do_in_ms, std::function<void()> action);
37
38 template <typename Action>
39 std::future<void> post(Action &&action) {
40 return post(0, std::forward<Action>(action));
41 }
42
43 struct Periodicity {
44 uint64_t period_ms = 0, delay_ms = period_ms;
45 };
46 void post_loop(Periodicity const &periodicity, std::function<void()> action);
47};
48} // namespace taraxa::util
Definition thread_pool.hpp:7
uint64_t num_pending_tasks() const
Definition thread_pool.hpp:26
std::atomic< uint64_t > num_pending_tasks_
Definition thread_pool.hpp:14
std::future< void > post(uint64_t do_in_ms, asio_callback action)
Definition thread_pool.cpp:36
ThreadPool(ThreadPool const &)=delete
~ThreadPool()
Definition thread_pool.cpp:73
ThreadPool & operator=(ThreadPool const &)=delete
ThreadPool & operator=(ThreadPool &&)=delete
auto & unsafe_get_io_context()
Definition thread_pool.hpp:29
std::future< void > post(Action &&action)
Definition thread_pool.hpp:39
void stop()
Definition thread_pool.cpp:25
boost::asio::io_context ioc_
Definition thread_pool.hpp:10
bool is_running() const
Definition thread_pool.cpp:23
boost::asio::executor_work_guard< decltype(ioc_)::executor_type > ioc_work_
Definition thread_pool.hpp:11
uint64_t delay_ms
Definition thread_pool.hpp:44
ThreadPool(ThreadPool &&)=delete
std::function< void(boost::system::error_code const &)> asio_callback
Definition thread_pool.hpp:8
std::vector< std::thread > threads_
Definition thread_pool.hpp:12
void post_loop(Periodicity const &periodicity, std::function< void()> action)
Definition thread_pool.cpp:66
auto capacity() const
Definition thread_pool.hpp:25
uint64_t period_ms
Definition thread_pool.hpp:44
void start()
Definition thread_pool.cpp:14
Definition thread_pool.hpp:43
Definition default_construct_copyable_movable.hpp:10