Boost ASIO write hang when device disconnects

  asio, boost, c++, multithreading

I have a server application that uses boost ASIO to communicate with several clients. The server application runs on a Linux server and the clients run on Windows desktops.

The current design is multi-threaded although there is only one boost ASIO thead (which runs boost::asio::io_context). The boost ASIO thread is only responsible for reading, writing, and some infrequent dispatch. Reading is done using boost::asio::async_read but copies the resulting message so that another thread can do the work of processing. Writing is done using boost::asio::write but the message has already been copied and handed off to the boost ASIO thread

Under most circumstances when a client disconnects boost ASIO throws an error, I shut down the associated socket, and the other sockets keep working. However if a client’s Windows desktop has a power failure while boost::asio::write is writing to them then boost does not detect an issue and hangs in boost::asio::write. It hangs for almost 20 minutes sometimes and the server cannot communicate with other clients during this time

From what I have read online the authors of boost ASIO have no intention of introducing a timeout parameter. I tried setting SO_SNDTIMEO to 5 seconds but that didn’t have any affect on the write hang. As of now my best guess to solve the issue is to give every socket a different thread so that one client cannot take down the other clients. Are there any better options than this? If I do give every socket its own thread does that mean I will need a boost::asio::io_context per thread to avoid the write hang?

Source: Windows Questions C++

LEAVE A COMMENT