'Use asio for concurrent server

I'm using asio to run a TCP server. For each message the server receives, one or more responses is returned.

Most of the messages are simple returns but some are commands which will run an action, which can take up to 10 minutes then a returns a message (but only one action can run at a time).

I start my session function in a new thread, passing it a tcp::socket when a connection is made:

tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port));
    for (;;) {
        std::thread(session, a.accept()).detach();
    }

But after that the tcp::socket is "stuck" in the session function. I can't pass the socket anywhere else (without compilation errors so far) and the session needs to be complete because it:

  1. Receives the message using socket.read_some()
  2. Processes the message (and trigger an action if required)
  3. Transmits a response using asio::write()

I need to be able to interrupt step 2 if a new message is received but without sharing the Socket I don't know how.

Whichever way I look at it, the socket can only be used by one thread so I'll either be waiting for a new message or waiting for a response to be generated - both of which would block eachother.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source