Skip to content
This repository has been archived by the owner on Jun 30, 2021. It is now read-only.

Commit

Permalink
served: ensure multithreaded servers are properly released
Browse files Browse the repository at this point in the history
 * A class destructor is added to properly release the members
 * The threads are joined upon destruction to ensure work is done
 * A 1 millisecond delay is added to avoid multithreading races
 * Threads are create with "bind" references rather than lambdas
  • Loading branch information
AdrianDC authored and Adrian Dubuc-Caldirac committed Aug 24, 2019
1 parent b8cf08d commit 64a9c5b
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
36 changes: 29 additions & 7 deletions src/served/net/server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@

#include <signal.h>
#include <utility>
#include <thread>

#include <served/net/server.hpp>

Expand Down Expand Up @@ -71,6 +70,30 @@ server::server( const std::string & address
do_accept();
}

server::~server()
{
_acceptor.close();
_connection_manager.stop_all();

if ( ! _io_service.stopped() )
{
_io_service.stop();
}

if ( _threads.size() > 0 ) {
for ( auto & thread : _threads )
{
if ( thread.joinable() )
{
thread.join();
}
}

std::this_thread::sleep_for(std::chrono::milliseconds(1));
_threads.clear();
}
}

void
server::run(int n_threads /* = 1 */, bool block /* = true */)
{
Expand All @@ -82,14 +105,13 @@ server::run(int n_threads /* = 1 */, bool block /* = true */)
*/
if ( n_threads > 1 )
{
std::vector<std::thread> v_threads;
for ( int i = 0; i < n_threads; i++ )
for ( int i = 0; i < 1; i++ )
{
v_threads.push_back(std::thread([this](){
_io_service.run();
}));
_threads.push_back(std::thread(
std::bind(static_cast<size_t(boost::asio::io_service::*)()>(
&boost::asio::io_service::run), std::ref(_io_service))));
}
for ( auto & thread : v_threads )
for ( auto & thread : _threads )
{
if ( block )
{
Expand Down
7 changes: 7 additions & 0 deletions src/served/net/server.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

#include <boost/asio.hpp>
#include <string>
#include <thread>
#include <served/net/connection_manager.hpp>
#include <served/multiplexer.hpp>

Expand All @@ -49,6 +50,7 @@ class server
int _read_timeout;
int _write_timeout;
size_t _req_max_bytes;
std::vector<std::thread> _threads;

public:
server(const server&) = delete;
Expand All @@ -70,6 +72,11 @@ class server
, multiplexer & mux
, bool register_signals = true );

/*
* Destroys the server.
*/
~server();

/*
* A call that prompts the server into listening for HTTP requests.
*
Expand Down

0 comments on commit 64a9c5b

Please sign in to comment.