I am currently writing a HTTP server. It blocks while waiting for socket-data (using boost::asio::ip::tcp::acceptor async_accept). Then when data is available creates a Session to handle the incoming request. The Session object calls Boost's http:async_read, a process_request method I wrote, then http::async_write.
We are trying to multithread the server. One idea would be to spawn X number of threads, all executing the start_accept function and listening on the same socket. Yet, I am not sure if this works using the Boost libraries (and can't figure it out from the docs).
TLDR; how does the Boost async read/write/accept functions work? Intuitively, I would think the OS routes incoming data to one of the threads, if each thread is blocking with async_accept. Are the async methods blocking across threads (and so thread safe)?
Here is the example where I am calling async_accept, then calling the Session object.
void Server::start_accept()
{
// Start acceptor.
m_acceptor.async_accept(m_socket, [&](beast::error_code error_code)
{
// After the accept operation completes
if (!error_code)
{
// Constructs a Session object then runs start()
std::make_shared<Session>(std::move(m_socket), m_server_params)->start();
}
start_accept(); // Accept new request.
});
}
I am envisioning some wrapper function that runs as follows:
void Server::start_multithreaded_server()
{
// Spawn X threads
create_thread(start_accept)
}