C++0x thread interruption

According to the C++0x final draft, there's no way to request a thread to terminate. That said, if required we need to implement a do-it-yourself solution.

On the other hand boost::thread provides a mechanism to interrupt a thread in a safe manner.

In your opinion, what's the best solution? Designing your own cooperative 'interruption mechanism' or going native?


Solution 1:

All the language specification says that the support isn't built into the language. boost::thread::interrupt needs some support from the thread function, too:

When the interrupted thread next executes one of the specified interruption points (or if it is currently blocked whilst executing one)

i.e. when the thread function doesn't give the caller a chance to interrupt, you are still stuck.

I'm not sure what you mean with "going native" - there is no native support, unless you are spellbound to boost:threads.

Still, I'd use an explicit mechanism. You have to think about having enough interruption points anyway, why not make them explicit? The extra code is usually marginal in my experience, though you may need to change some waits from single-object to multiple-objects, which - depending on your library - may look uglier.


One could also pull the "don't use exceptions for control flow", but compared to messing around with threads, this is just a guideline.

Solution 2:

Using native handle to cancel a thread is a bad option in C++ as you need to destroy all the stack allocated objects. This was the main reason they don't included a cancel operation.

Boost.Thread provides an interrupt mechanism, that needs to pool on any waiting primitive. As this can be expensive as a general mechanism, the standard has not included it.

You will need to implement it by yourself. See my answer here to a similar question on how to implement this by yourself. To complete the solution an interruption should be throw when interrupted is true and the thread should catch this interruption and finish.