diff --git a/ext/native/net/http_server.cpp b/ext/native/net/http_server.cpp index 1c0b5995b3..c4120bae6a 100644 --- a/ext/native/net/http_server.cpp +++ b/ext/native/net/http_server.cpp @@ -131,6 +131,10 @@ Server::Server(threading::Executor *executor) SetFallbackHandler(std::bind(&Server::Handle404, this, std::placeholders::_1)); } +Server::~Server() { + delete executor_; +} + void Server::RegisterHandler(const char *url_path, UrlHandlerFunc handler) { handlers_[std::string(url_path)] = handler; } diff --git a/ext/native/net/http_server.h b/ext/native/net/http_server.h index 2c84c4d283..0b5dfbe668 100644 --- a/ext/native/net/http_server.h +++ b/ext/native/net/http_server.h @@ -62,8 +62,9 @@ private: // Register handlers on this class to serve stuff. class Server { public: + // Takes ownership. Server(threading::Executor *executor); - virtual ~Server() {} + virtual ~Server(); typedef std::function UrlHandlerFunc; typedef std::map UrlHandlerMap; diff --git a/ext/native/thread/executor.cpp b/ext/native/thread/executor.cpp index 197f9d7920..e20fac09b1 100644 --- a/ext/native/thread/executor.cpp +++ b/ext/native/thread/executor.cpp @@ -10,7 +10,13 @@ void SameThreadExecutor::Run(std::function func) { } void NewThreadExecutor::Run(std::function func) { - std::thread(func).detach(); + thread_ = std::thread(func); +} + +NewThreadExecutor::~NewThreadExecutor() { + // If Run was ever called... + if (thread_.joinable()) + thread_.join(); } } // namespace threading diff --git a/ext/native/thread/executor.h b/ext/native/thread/executor.h index 6d6515920c..6a3122e920 100644 --- a/ext/native/thread/executor.h +++ b/ext/native/thread/executor.h @@ -1,6 +1,7 @@ #pragma once #include +#include namespace threading { @@ -8,6 +9,7 @@ namespace threading { class Executor { public: virtual void Run(std::function func) = 0; + virtual ~Executor() {} }; class SameThreadExecutor : public Executor { @@ -17,7 +19,11 @@ public: class NewThreadExecutor : public Executor { public: + ~NewThreadExecutor() override; void Run(std::function func) override; + +private: + std::thread thread_; }; } // namespace threading