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

I have a program that uses a third party library to do some calculations that I run in a separate thread from my main application. Unfortunately, this calculation can take a very long time and does not provide an interface for updating and canceling progress.

To have such an interface, I want to create a Cancel button that should immediately stop the calculation (and delete all results).

I will need some help (-coded trimmed code) on how this is best set up and done. Is it safe?

I am currently using AfxBeginThread()

to start a process.

+3


source to share


2 answers


Killing (or suspending) a thread that is not running your code is an exercise in breaking your program.

If there is code in the stream that

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

      

The cs resource will then be permanently owned by the destroyed (or suspended thread). This will then be slowed down when the resource is needed elsewhere.



If the thread creates other resources like files, shared memory, they can also be missed, adding to your program instability.

If the thread has a cancellation callback, that should be used. I've also tried the error insertion forms where the thread was requesting data and they ended up "testing" the third-party code, leaving untested and erroneous paths running.

Talk to the provider and ask for a cancellation method or find alternatives.

+4


source


I suggest creating a child process to do this lengthy computation. Unlike a thread, a process can be terminated without adversely affecting the main application. This approach will also protect the main application in the event of critical errors in third-party code, such as an access violation, which would otherwise kill it.



+2


source







All Articles