Kylin/Universal/IoContext.h

51 lines
1.7 KiB
C
Raw Normal View History

2023-07-21 11:21:16 +08:00
#ifndef IOCONTEXT_H
#define IOCONTEXT_H
#include "Singleton.h"
#include <boost/asio/io_context.hpp>
2024-09-15 23:39:23 +08:00
#include <boost/asio/post.hpp>
#include <boost/asio/steady_timer.hpp>
2023-07-21 11:21:16 +08:00
#include <thread>
class IoContext {
public:
friend class Amass::Singleton<IoContext, Amass::LocalInstance>;
2024-09-15 23:39:23 +08:00
std::shared_ptr<boost::asio::io_context> ioContext() const {
return m_ioContext;
}
2024-11-10 18:02:28 +08:00
void run(bool asynchronous = true) ;
2024-09-07 21:54:50 +08:00
void stop();
2023-07-21 11:21:16 +08:00
~IoContext();
2024-09-15 23:39:23 +08:00
/**
2024-11-10 18:02:28 +08:00
* @brief
*
2024-09-15 23:39:23 +08:00
* @tparam Executor boost::asio::io_contextboost::asio::strand( boost::asio::make_strand(io_context); )
*/
template <class Executor, class Func, class Rep, class Period>
static void postDelayed(Executor &ioContext, Func &&task, const std::chrono::duration<Rep, Period> &duration) {
auto timer = std::make_shared<boost::asio::steady_timer>(ioContext, duration);
timer->async_wait([timer, task = std::forward<Func>(task)](const boost::system::error_code & /*e*/) mutable {
boost::asio::post(timer->get_executor(), std::move(task));
});
}
template <class Executor, class Func>
static void postDelayed(Executor &ioContext, Func &&task, int milliseconds) {
return postDelayed(ioContext, std::forward(task), std::chrono::milliseconds(milliseconds));
}
2023-07-21 11:21:16 +08:00
protected:
2024-11-10 18:02:28 +08:00
IoContext(int concurrency);
2023-07-21 11:21:16 +08:00
void runIoContext();
private:
2024-11-10 18:02:28 +08:00
int m_concurrency = 1;
2023-07-21 11:21:16 +08:00
std::shared_ptr<boost::asio::io_context> m_ioContext;
2024-11-10 18:02:28 +08:00
std::unique_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> m_guarder;
std::vector<std::thread> m_threads;
bool m_asynchronous=false;
2023-07-21 11:21:16 +08:00
};
#endif // IOCONTEXT_H