multithreadingdelphidelphi-7tthread

Free a TThread either automatically or manually


I have a main thread and a separate thread in my program. If the separate thread finishes before the main thread, it should free itself automatically. If the main thread finishes first, it should free the separate thread.

I know about FreeOnTerminate, and I've read that you have to be careful using it.

My question is, is the following code correct?

procedure TMyThread.Execute;
begin
  ... Do some processing

  Synchronize(ThreadFinished);

  if Terminated then exit;

  FreeOnTerminate := true;
end;

procedure TMyThread.ThreadFinished;
begin
  MainForm.MyThreadReady := true;
end;

procedure TMainForm.Create;
begin
  MyThreadReady := false;

  MyThread := TMyThread.Create(false);
end;

procedure TMainForm.Close;
begin
  if not MyThreadReady then
  begin
    MyThread.Terminate;
    MyThread.WaitFor;
    MyThread.Free;
  end;
end;

Solution

  • You can simplify this to:

    procedure TMyThread.Execute;
    begin
      // ... Do some processing
    end;
    
    procedure TMainForm.Create;
    begin
      MyThread := TMyThread.Create(false);
    end;
    
    procedure TMainForm.Close;
    begin
      if Assigned(MyThread) then
        MyThread.Terminate;
      MyThread.Free;
    end;
    

    Explanation:

    BTW: Don't use the OnClose event, use OnDestroy instead. The former isn't necessarily called, in which case your thread would maybe continue to run and keep your process alive.