views:

159

answers:

2

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?

+3  A: 

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.

Vicente Botet Escriba
I think I'll keep using Boost threads then. They are buggy too, but at least I have a stable workaround for them.
doublep
A: 

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 thread class based on std::thread with the mechanism.

Gaetano Mendola
And presumably write my own condition subclass so that thread knows what it waits for? This sounds like a bit too much work to me.
doublep