Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interrupt boost::asio synchronous read?

I'm using asio synchronous sockets to read data over TCP from a background thread. This is encapsulated in a "server" class.

However, I want the thread to exit when the destructor of this class is called. The problem is that a call to any of the read functions does block, so the thread cannot be easily terminated. In Win32 there is an API for that: WaitForMultipleObjects which would do exactly what I want.

How would I achieve a similar effect with boost?

like image 929
SDD Avatar asked Dec 06 '09 23:12

SDD


1 Answers

In our application, we set the "terminating" condition, and then use a self-connection to the port that the thread is listening on so it wakes up, notes the terminate condition and terminate.

You could also check the boost implementation - if they are only doing a plain read on the socket (i.e., not using something like WaitForMultipleObjects internally themselves) then you can probably conclude that there isn't anything to simply and cleanly unblock the thread. If they are waiting on multiple objects (or a completion port) you could dig around to see if the ability to wake blocking thread is exposed to the outside.

Finally, you could kill the thread - but you'll have to go outside of boost to do this, and understand the consequences, such as dangling or leaked resources. If you are shutting down, this may not be a concern, depending on what else that thread was doing.

like image 198
BeeOnRope Avatar answered Oct 04 '22 09:10

BeeOnRope