#ifndef IOCONTEXT_H #define IOCONTEXT_H #include "Singleton.h" #include #include #include #include class IoContext { public: enum class Mode { Synchronous, Asynchronous, }; friend class Amass::Singleton; std::shared_ptr ioContext() const { return m_ioContext; } template void run() { if constexpr (mode == Mode::Asynchronous) { m_thread = std::thread(&IoContext::runIoContext, this); } else { runIoContext(); } } void stop(); ~IoContext(); /** * @brief * * @tparam Executor boost::asio::io_context、boost::asio::strand(通过 boost::asio::make_strand(io_context); 得到) */ template static void postDelayed(Executor &ioContext, Func &&task, const std::chrono::duration &duration) { auto timer = std::make_shared(ioContext, duration); timer->async_wait([timer, task = std::forward(task)](const boost::system::error_code & /*e*/) mutable { boost::asio::post(timer->get_executor(), std::move(task)); }); } template static void postDelayed(Executor &ioContext, Func &&task, int milliseconds) { return postDelayed(ioContext, std::forward(task), std::chrono::milliseconds(milliseconds)); } protected: template IoContext(Args &&...args) : m_ioContext(std::make_shared(std::forward(args)...)) { } void runIoContext(); private: std::thread m_thread; std::shared_ptr m_ioContext; }; #endif // IOCONTEXT_H