Kylin/Universal/IoContext.h
2024-09-15 23:39:23 +08:00

61 lines
1.9 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:
enum class Mode {
Synchronous,
Asynchronous,
};
friend class Amass::Singleton<IoContext, Amass::LocalInstance>;
std::shared_ptr<boost::asio::io_context> ioContext() const {
return m_ioContext;
}
template <Mode mode = Mode::Asynchronous>
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 <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:
template <typename... Args>
IoContext(Args &&...args) : m_ioContext(std::make_shared<boost::asio::io_context>(std::forward<Args>(args)...)) {
}
void runIoContext();
private:
std::thread m_thread;
std::shared_ptr<boost::asio::io_context> m_ioContext;
};
#endif // IOCONTEXT_H