BmyGuest
BmyGuest

Reputation: 2949

How can I (safely) interrupt a computation on a separate thread?

I have a program which uses a 3rd party library to do some computation which I launch on a separate thread from my main application. Unfortunately, this computation can take extremely long and does not provide an interface for progress updates and cancellation.

In order to have such an interface, I want to create a "Cancel" button which should immediately terminate the computation (and trash all results).

I would require some help (-code snipped appreciated-) with how this is best set-up and cleanly executed. Is it 'safe' to do it?

I'm currently using AfxBeginThread() to launch the process.

Upvotes: 3

Views: 189

Answers (2)

user7860670
user7860670

Reputation: 37549

I suggest to spawn a child process to perform these long computations. Unlike thread, a process can be terminated without negative consequences for main application. This approach will also protect main application in case of critical errors in third-party code, such as access violation that would otherwise kill it.

Upvotes: 2

mksteve
mksteve

Reputation: 13073

Destroying (or pausing) a thread which is not running your code, is an exercise in breaking your program.

If there is code within the thread which

EnterCriticalSection( &cs );
// do something
LeaveCriticalSection( &cs );

Then the resource cs will be permanently owned by the destroyed (or paused thread). This will then deadlock when the resource is required anywhere else.

If the thread is creating other resources such as files, shared memory, these can also be leaked adding to your programs instability.

If the thread has a cancel call-back, this should be used. I have also tried forms of error injection, when the thread was asking for data, and these ended up "testing" the third-party code, leaving it executing untested and buggy paths.

Talk to the supplier and ask for a cancel method, or look for alternatives.

Upvotes: 4

Related Questions