Reputation: 37
The four common methods to kill threads I've read are:
Method four solves my problem but from what I understand, it is taboo to use so I just want to make sure that methods one to three do not work for me.
There is no sleeping or waiting so method one doesn't work. There is no while loop but there are several for loops so method two doesn't work. I only have one thread with no synchronization with other threads, so method three doesn't work. Therefore, I would be correct in using method four, right?
My application does a CPU-intensive algorithm on one thread. When the user exits the GUI, I want the computation to stop.
Upvotes: 1
Views: 74
Reputation: 10466
I Personally prefer method 2 Poll a flag variable
, And I do not see why you can't use it as well.
So, You have several for
loops, right? try the following:
for(int i=0; i< data1.length && !abortFlag; i++)
{
//Do stuff
for(int j=0; j< data2.length && !abortFlag; j++)
{
//Do more stuff
for(int k=0; k< data3.length && !abortFlag; k++)
{
//Do even more stuff
}
}
}
Once you want to abort, simply set abortFlag = true;
One last thing. I think it is important to understand that there is no real difference between for
and while
loops. The difference is only semantics, you can accomplish same tasks with both.
EDIT
As per @Patrik's comment, when you share a variable for the purpose of managing threads (abortFlag
in this case), it should be it should be marked as volatile: volatile int i;
Upvotes: 1