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

doublep picture doublep · May 17, 2010 · Viewed 7.4k times · Source

I'm considering to use C++0x threads in my application instead of Boost threads. However, I'm not sure how to reimplement what I have with standard C++0x threads since they don't seem to have an interrupt() method.

My current setup is:

  • a master thread that manages work;
  • several worker threads that carry out master's commands.

Workers call wait() on at least two different condition variables. Master has a "timed out" state: in this case it tells all workers to stop and give whatever result they got by then. With Boost threads master just uses interrupt_all() on a thread group, which causes workers to stop waiting. In case they are not waiting at the moment, master also sets a bool flag which workers check periodically.

However, in C++0x std::thread I don't see any replacement for interrupt(). Do I miss something? If not, how can I implement the above scheme so that workers cannot just sleep forever?

Answer

Vicente Botet Escriba picture Vicente Botet Escriba · May 17, 2010

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.