Kill a blocked Boost::Thread

boost-thread, c++, iostream

Solution

I don't think there is a way to do it cross platform, but pthread_cancel should be what you are looking for. With a boost thread you can get the native_handle from a thread, and call pthread_cancel on it.

In addition a better way might be to use the boost asio equivalent of a select call on multiple files. That way one thread will be blocked waiting for the input, but it could come from either input stream. I don't know how easy it is to do something like this with iostreams though.

Problem

I am writing an application which blocks on input from two `istreams`. Reading from either `istream` is a synchronous (blocking) call, so, I decided to create two `Boost::thread`s to do the reading. Either one of these threads can get to the "end" (based on some input received), and once the "end" is reached, both input streams stop receiving. Unfortunately, I cannot know which will do so. Thus, I cannot `join()` on both threads, because only one thread (cannot be predetermined which one) will actually return (unblock). I must somehow force the other to exit, but it is blocked waiting for input, so it cannot itself decide it is time to return (condition variables or what not). Is their a way to either: - Send a signal a boost::thread, or - Force an `istream` to "fail", or - Kill a Boost::thread? Note: - One of the `istreams` is `cin` - I am trying to restart the process, so I cannot close the input streams in a way that prohibits reseting them. Edit: - I do know when the "end" is reached, and I do know which thread has successfully finished, and which needs to be killed. Its the killing I need to figure out (or a different strategy for reading from an istream). - I need both threads to exit and cleanup properly :( Thanks!

Original source