Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when you terminate() a Thread (class TThread), does it exit every child of this thread?

I have a code in Delphi which does the following:

procedure THilo.Execute; // (which is the thread)
begin
  inherited;
  FreeOnTerminate := True;
  while not Terminated do
  begin
    (...)
    Sleep(100);
  end;
end;

and now somewhere else, in another thread (or the GUI) we do this:

var
  Hilo2: THilo;
begin
  Hilo2 := THilo.Create(True);
  Hilo2.start;
  Hilo2 := THilo.Create(True);
  Hilo2.start;
end;

now we have executed 2 times the same thread, and they are running in parallel. What happens if we do now this?:

  Hilo2.Terminate;

will this terminate both threads or just 1, or what? also, if we would like to terminate it, could we achieve this by .Resume()?

Thanks in advance

like image 674
user2308704 Avatar asked May 21 '13 22:05

user2308704


1 Answers

When you create the second thread you are overwriting the local variable Hilo2 with a pointer to the second object - the first object's pointer is lost and you no longer have any reference to it (or way to control it). This will result in a memory leak if the thread does not terminate itself and, no, calling terminate will not stop both threads, only the one last created with that variable as reference. Also, there is no need to call inherited in the Execute method of a TThread - there is nothing to inherit (TThread's execute method is abstract, it doesn't do anything).

like image 83
J... Avatar answered Nov 10 '22 00:11

J...