2023-07-21 11:21:16 +08:00
|
|
|
#include "IoContext.h"
|
|
|
|
#include <boost/asio/executor_work_guard.hpp>
|
|
|
|
#include <boost/scope_exit.hpp>
|
2024-05-05 17:21:45 +08:00
|
|
|
#include <boost/stacktrace.hpp>
|
2023-07-21 11:21:16 +08:00
|
|
|
|
2024-11-10 18:02:28 +08:00
|
|
|
IoContext::IoContext(int concurrency_hint)
|
|
|
|
: m_concurrency(concurrency_hint), m_ioContext(std::make_shared<boost::asio::io_context>(concurrency_hint)) {
|
|
|
|
}
|
|
|
|
|
2023-07-21 11:21:16 +08:00
|
|
|
IoContext::~IoContext() {
|
2024-09-07 21:54:50 +08:00
|
|
|
stop();
|
|
|
|
}
|
|
|
|
|
|
|
|
void IoContext::stop() {
|
2024-11-10 18:02:28 +08:00
|
|
|
m_guarder.reset();
|
2023-07-21 11:21:16 +08:00
|
|
|
m_ioContext->stop();
|
2024-11-10 18:02:28 +08:00
|
|
|
if (!m_asynchronous) {
|
|
|
|
for (auto &thread : m_threads) {
|
|
|
|
if (thread.joinable()) thread.join();
|
|
|
|
}
|
|
|
|
m_threads.clear();
|
|
|
|
}
|
2023-07-21 11:21:16 +08:00
|
|
|
}
|
|
|
|
|
2024-11-10 18:02:28 +08:00
|
|
|
void IoContext::run(bool asynchronous) {
|
|
|
|
using namespace boost::asio;
|
|
|
|
if (m_concurrency < 1) m_concurrency = 1;
|
|
|
|
m_asynchronous = asynchronous;
|
|
|
|
for (int i = 0; i < m_concurrency; i++) {
|
|
|
|
m_threads.push_back(std::thread(&IoContext::runIoContext, this));
|
2023-07-21 11:21:16 +08:00
|
|
|
}
|
2024-11-10 18:02:28 +08:00
|
|
|
m_guarder = std::make_unique<executor_work_guard<io_context::executor_type>>(m_ioContext->get_executor());
|
|
|
|
if (asynchronous) {
|
|
|
|
for (auto &thread : m_threads) {
|
|
|
|
if (thread.joinable()) thread.join();
|
|
|
|
}
|
|
|
|
m_threads.clear();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
void IoContext::runIoContext() {
|
2023-07-21 11:21:16 +08:00
|
|
|
try {
|
|
|
|
m_ioContext->run();
|
|
|
|
} catch (const boost::log::system_error &error) {
|
|
|
|
LOG(error) << error.what();
|
|
|
|
} catch (const std::out_of_range &e) {
|
|
|
|
LOG(error) << e.what();
|
|
|
|
} catch (const boost::exception &e) {
|
|
|
|
LOG(error) << boost::diagnostic_information(e);
|
|
|
|
} catch (const std::exception &e) {
|
2024-08-27 14:14:27 +08:00
|
|
|
#if BOOST_VERSION < 108600
|
|
|
|
LOG(error) << e.what();
|
|
|
|
#else
|
2024-05-05 17:21:45 +08:00
|
|
|
boost::stacktrace::stacktrace trace = boost::stacktrace::stacktrace::from_current_exception();
|
|
|
|
LOG(error) << e.what() << ", trace:\n" << trace;
|
2024-08-27 14:14:27 +08:00
|
|
|
#endif
|
2023-07-21 11:21:16 +08:00
|
|
|
}
|
|
|
|
}
|