I am using Boost.Asio and Boost.Thread. How can I cancel a synchronous IO operation in a secondary Thread? For example,
/* consider needed headers included and typedefs are defined */
void OperationThread(sock_ptr sock) {
char buf[128];
boost::system::error_code ec;
boost::asio::read(*sock, boost::asio::buffer(buf, 128), ec);
}
void AcceptorThread() {
boost::asio::io_service serv;
boost_asio_endpoint_type ep( ... /* v4() etc. */ , ... /* port */ );
boost_asio_acceptor_type acc(serv, ep);
sock_ptr sock(new boost_asio_socket_type(serv));
while (true) {
acc.accept(*sock);
boost::thread t(boost::bind(&OperationThread, sock)); // new thread
sock.reset(new boost_asio_socket_type(serv)); // new socket
}
}
int main() {
boost::thread accthread(&AcceptorThread);
cin.get();
// Code to cancel synchronous accept operation and read operations
return 0;
}
sock_ptr
is a typedef of boost::shared_ptr<boost_asio_socket_type>
.
If you get confused about boost_asio_*_type
consider they are configured for boost::asip::ip::tcp
and v4()
.
First of all I used to use asynchronous operations. But you know they are a little bit hard to manage. And I want one-thread-per-connection application model. It's harder to implement it using asynchronous IO (actually I don't know how to implement it, how can I poll a specific asynchronous operation in a thread?, I'd be happy if you mention.). So I use synchronous IO.
And in my code, as you would notice, my thread object destroyed at the end of while block. Does it make any harm? (sorry I know it is not appropriate to ask it in this question, but anyone who wants to do what I am trying to do may face this question. So if you answer, I will be very happy. ʘ‿ʘ)
Thanks.