How to interrupt a waiting C++0x thread? How to interrupt a waiting C++0x thread? multithreading multithreading

How to interrupt a waiting C++0x thread?


Unfortunately I don't see another way than polling, instead of using wait use a timed wait and a variable to state the interruption has been done.

void th(Interruptor& interruptor) {  try {    ...    while (cnd1.timed_wait(d)==false) {      interruptor.check_interruption_point();    }    ...  } catch (interrupted_exception &) {}}

The Interruptor class will maintain a boolean variable protected with a mutex or using atomic operations if you have them and two functions interrupt and check_interruption_point, which with throw a interrupted_exception if the boolean is true. The Mater thread will create an Interruptor variable that will be given to the concerned threads at creation time. The master has the the possibility to interrupt at once all the threads that depends on this interruptor. You can of course create an interruptor for each thread if you want to explicitly interrupt one thread at a time.

Up to you to define the duration on the timed wait, so your threads are able to react as soon as your program require.


Wait boost does on the interrupt() is to emit a notify_all on the condition a thread is currently blocked and then check if an interruption was requested. If an interruption was requested then it does a throw boost::thread_interrupted. You can write a your own threadclass based on std::thread with the mechanism.


Indeed, C++11 std::thread does not offer a standard mechanism for this (yet?). Therefore I second @doublep's decision to use boost::thread for the time being.

We'd prefer to use C++11 std:: facilities. But we don't want to re-build boost's terminate() facility, complete with condition variable futzing to interrupt sleeps etc., for no reason. Creating infrastructure like that is fun, and not that difficult, but unproductive and less standard than using boost.

It helps that boost::thread and std::thread are so similar that we feel we're not painting ourself into a corner. (We expect eventual migration to std::thread to be relatively easy, perhaps even trivial.)