1717#include < sys/types.h>
1818#endif
1919
20+ #include < future>
2021#include < memory>
2122#include < string>
2223#include < thread>
@@ -126,10 +127,13 @@ class Server : public std::enable_shared_from_this<Server>
126127
127128 void Stop ()
128129 {
130+ auto stop_promise = std::make_shared<std::promise<void >>();
131+ auto stop_future = stop_promise->get_future ();
132+
129133 // Posting the close to the acceptors strand ensures
130134 // we do not have a race condition with async_accept.
131135 boost::asio::post (acceptor.get_executor (),
132- [self = shared_from_this ()]()
136+ [self = shared_from_this (), stop_promise ]()
133137 {
134138 boost::beast::error_code ec;
135139 (void )self->acceptor .close (ec);
@@ -139,7 +143,11 @@ class Server : public std::enable_shared_from_this<Server>
139143 }
140144 // Stop the io_context
141145 self->io_context .stop ();
146+ stop_promise->set_value ();
142147 });
148+
149+ // The above function is async, this simply waits until it succeeded
150+ stop_future.wait ();
143151 }
144152
145153 void RegisterServiceHandler (std::unique_ptr<ServiceHandlerInterface> service_handler_)
@@ -152,9 +160,14 @@ class Server : public std::enable_shared_from_this<Server>
152160 {
153161 // The new connection gets its own strand
154162 acceptor.async_accept (boost::asio::make_strand (io_context),
155- [self = shared_from_this ()](boost::beast::error_code ec,
156- boost::asio::ip::tcp::socket socket)
157- { self->OnAccept (ec, std::move (socket)); });
163+ [weak_self = std::weak_ptr<Server>(shared_from_this ())](
164+ boost::beast::error_code ec, boost::asio::ip::tcp::socket socket)
165+ {
166+ if (auto self = weak_self.lock ())
167+ {
168+ self->OnAccept (ec, std::move (socket));
169+ }
170+ });
158171 }
159172
160173 void OnAccept (boost::beast::error_code ec, boost::asio::ip::tcp::socket socket)
0 commit comments