Skip to content
Snippets Groups Projects
Commit b04fbd7e authored by Adrien Béraud's avatar Adrien Béraud
Browse files

upnp: use dedicated io_context if none provided

Change-Id: I8482f636007e3625576f5fc9f6f95c3d5be6d2bb
parent c161aaa5
No related branches found
No related tags found
No related merge requests found
......@@ -107,6 +107,8 @@ public:
UPnPContext(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger);
~UPnPContext();
std::shared_ptr<asio::io_context> createIoContext(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger);
// Terminate the instance.
void shutdown();
......@@ -311,6 +313,9 @@ private:
// Shutdown synchronization
bool shutdownComplete_ {false};
// Thread
std::unique_ptr<std::thread> ioContextRunner_;
};
} // namespace upnp
......
......@@ -44,7 +44,7 @@ constexpr static uint16_t UPNP_UDP_PORT_MIN {20000};
constexpr static uint16_t UPNP_UDP_PORT_MAX {UPNP_UDP_PORT_MIN + 5000};
UPnPContext::UPnPContext(const std::shared_ptr<asio::io_context>& ioContext, const std::shared_ptr<dht::log::Logger>& logger)
: mappingListUpdateTimer_(*ioContext), ctx(ioContext), logger_(logger)
: ctx(createIoContext(ioContext, logger)), mappingListUpdateTimer_(*ioContext), logger_(logger)
{
if (logger_) logger_->debug("Creating UPnPContext instance [{}]", fmt::ptr(this));
......@@ -55,6 +55,25 @@ UPnPContext::UPnPContext(const std::shared_ptr<asio::io_context>& ioContext, con
ctx->post([this] { init(); });
}
std::shared_ptr<asio::io_context>
UPnPContext::createIoContext(const std::shared_ptr<asio::io_context>& ctx, const std::shared_ptr<dht::log::Logger>& logger) {
if (ctx) {
return ctx;
} else {
if (logger) logger->debug("UPnPContext: starting dedicated io_context thread");
auto ioCtx = std::make_shared<asio::io_context>();
ioContextRunner_ = std::make_unique<std::thread>([ioCtx, l=logger]() {
try {
auto work = asio::make_work_guard(*ioCtx);
ioCtx->run();
} catch (const std::exception& ex) {
if (l) l->error("Unexpected io_context thread exception: {}", ex.what());
}
});
return ioCtx;
}
}
void
UPnPContext::shutdown(std::condition_variable& cv)
{
......@@ -75,6 +94,13 @@ UPnPContext::shutdown(std::condition_variable& cv)
shutdownComplete_ = true;
cv.notify_one();
}
if (ioContextRunner_) {
if (logger_) logger_->debug("UPnPContext: stopping io_context thread");
ctx->stop();
ioContextRunner_->join();
ioContextRunner_.reset();
}
}
void
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment