Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill a thread without MyThread.Terminate

In a form I have a button, "Abort". On it I have added mythread.terminate for killing a thread. Now in the execute method I use a variable, terminated, and manage it. But when I haven't a cycle, but a single instruction that take much time, as I can kill the thread?

For example, the code is:

procedure MyThread.Execute;
begin
    Sleep (10000);
end;

and I want kill the thread before it finishes work, as I do? Using:

MyThread.Terminate

the a pplication freeze.

Update:

Using while not terminate, can to be valid this solution, in sense it work:

flag := false;
while not terminated do
begin
    if not flag then
    begin
        xxx := myfunction ();
        flag := true;
        terminate;
    end;
end

Solved:

I have tried to do so, and I just have the impression that it works fine:

procedure MyThread.Execute;
begin
    FreeOnTerminate := True;
    while not Terminated do
    begin
        Sleep (10000); // Just an example for take long time.
        Terminate; // This will set Terminated to True, so it won't iterate next time.
    end;
end;

What should I do?

like image 684
Marcello Impastato Avatar asked May 01 '26 17:05

Marcello Impastato


1 Answers

If you have a single method call that takes a long time, then the best solution is to make changes inside that single method call to regularly check for termination.

Forcibly terminating a thread leads to resource leaks, deadlocks, and the mass slaughter of innocent babies. Actually, I'm not 100% certain on the veracity of that final point, but I think you can understand what I'm trying to say—don't forcibly terminate threads.


If you don't have access to the internals of this long running method then you really are in a bind. I have been in that situation in the past and managed to solve the problem by corrupting the input data that was passed to the method. For example, in my case, I was passing large arrays of floating point values. Setting all of those floating point values to signalling NaN proved sufficient to make the long running method gag and return. Perhaps you will be able to use a similar method.

like image 65
David Heffernan Avatar answered May 04 '26 04:05

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!