Could I close tcp::socket in different thread from the sync-reading thread?
It looks like:
boost::asio::ip::tcp::socket* tcp_socket; //blocking mode
thread1:
while(true){
try{
std::vector<char> read_buffer(10);
tcp_socket->read_some( boost::asio::buffer( read_buffer ) );
}
catch(boost::system::system_error& e){
//TODO
break;
}
}
thread2:
tcp_socket->shutdown(boost::asio::ip::tcp::socket::shutdown_both);
tcp_socket->close();
I saw the document of tcp::socket. They say the object is thread-unsafty.But the demo code seems working well.
So Is it safe? What about tcp::acceptor? Could I invoke close and accept in multithreading
on same tcp::acceptor?
The documentation states that
tcp::socketis not thread safe for shared objects.Don’t count on it seemingly working as a guarantee that it will always work.
Moreover, closing a socket from another thread, at the socket layer, is not a portable way of getting the blocking thread to unblock.
Here’s what I would suggest:
Quoting the author on a similar question: