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?
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.
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.
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.)
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.