Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 202
Nicola Bonelli Avatar asked May 07 '10 17:05

Nicola Bonelli


People also ask

What does thread currentThread () interrupt () do?

By calling Thread. currentThread(). interrupt() , you set the interrupt flag of the thread, so higher-level interrupt handlers will notice it and can handle it appropriately.

What is thread interruption?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.

How do I interrupt a thread in C++?

When you want to interrupt a thread, you simply write synchronously to this variable, and then you join the thread. Assuming it cooperates appropriately, it should notice that that the variable has been written and shut down, resulting in the join function no longer blocking.

What happens if current thread is interrupted by another thread?

If the target thread does not poll the interrupted status the interrupt is effectively ignored. Polling occurs via the Thread. interrupted() method which returns the current thread's interrupted status AND clears that interrupt flag. Usually the thread might then do something such as throw InterruptedException.


1 Answers

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.

like image 108
peterchen Avatar answered Sep 22 '22 23:09

peterchen