I recommend that you create two io_services, the first one (which you can dispatch in a thread) should be used for all socket communication.) And the second (dispatching on the main thread) should handle the console activity.
For example:
main()
{
// Run the network service
std::thread service([]() { net_service.run(); });
// Now run the console service
console_service.run();
}
To communicate between the two services, use the io_service::post()
operation. This posts a handler onto the given io service which is executed in that context. For example.
client_socket.async_read_some(_data, [](...) {
// Now you have the data and you want to print it..
console_service.post([=]() { std::cout << "message " << _data << std::endl; });
});
So now when you read something from the client_socket
, you post that data to the console service - note it's important that either you copy the data or if you want to avoid the copies, create some separate queue like you have and simply use the post()
mechanism to notify the other io_service.
NOTE: The other answer mentions poll()
, this will cause the context to spin as it will return immediately if there is nothing to complete.