Kylin/Universal/IoContext.h
2024-11-10 18:02:28 +08:00

51 lines
1.7 KiB
C++

#ifndef IOCONTEXT_H
#define IOCONTEXT_H
#include "Singleton.h"
#include <boost/asio/io_context.hpp>
#include <boost/asio/post.hpp>
#include <boost/asio/steady_timer.hpp>
#include <thread>
class IoContext {
public:
friend class Amass::Singleton<IoContext, Amass::LocalInstance>;
std::shared_ptr<boost::asio::io_context> ioContext() const {
return m_ioContext;
}
void run(bool asynchronous = true) ;
void stop();
~IoContext();
/**
* @brief
*
* @tparam Executor boost::asio::io_context、boost::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));
}
protected:
IoContext(int concurrency);
void runIoContext();
private:
int m_concurrency = 1;
std::shared_ptr<boost::asio::io_context> m_ioContext;
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;
};
#endif // IOCONTEXT_H