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:
istream
to "fail", orNote:
istreams
is cin
Edit:
Thanks!
Use interrupt() . Also, you should define interruption points. Thread will be interrupted after calling interrupt() as soon as it reaches one of interruption points.
Boost. Thread is the library that allows you to use threads. Furthermore, it provides classes to synchronize access on data which is shared by multiple threads. Threads have been supported by the standard library since C++11.
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.
Yes there is!
boost::thread::terminate()
will do the job to your specifications.
It will cause the targeted thread to throw an exception. Assuming it's uncaught, the stack will unwind properly destroying all resources and terminating thread execution.
The termination isn't instant. (The wrong thread is running at that moment, anyway.)
It happens under predefined conditions - the most convenient for you would probably be when calling boost::this_thread::sleep();
, which you could have that thread do periodically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With