Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

terminate a thread in delphi

How can I terminate a thread in a proper way? When the thread finishes, it is still in memory. I'm using Delphi 2010 (Update 5).

like image 875
Mohamad Avatar asked Mar 14 '11 08:03

Mohamad


2 Answers

The way I usually describe the issues of thread termination is to stress co-operation. You should not terminate a thread. Instead you should notify the thread that you want it to terminate. You then politely wait until it has terminated.

The reasons for this are manifest. Only the thread knows how to terminate itself. Only the thread knows what locks it holds, what resources it needs to free etc.

The same arguments apply if you wish to pause or suspend a thread's execution. You should ask to it do so and then let the thread find a convenient moment when it is safe to do so.

With a Delphi TThread the standard way to request termination is to call Thread.Terminate. This does nothing more than to set a flag in the thread object. That is the request. The response is initiated by the thread code inside TThread.Execute. That should regularly check the value of its Terminated property. When that is found to be true, it should exit from the function. Naturally any tidy up (release locks, return resources etc.) should be performed before calling exit.

like image 138
David Heffernan Avatar answered Oct 24 '22 18:10

David Heffernan


How exactly do you terminate a thread? If you just set Terminate, this is just a flag checked inside of the thread. If you need to terminate thread of execution (and not signal a TThread object that it needs to finish), you can use TerminateThread WinAPI function. But you should notice that this leads to resource leaks (as written in the comments in documentation for TerminateThread).

like image 24
Eugene Mayevski 'Callback Avatar answered Oct 24 '22 18:10

Eugene Mayevski 'Callback