TThread - Why can't I start a thread again? lazarus / 21-General ---------------------------------------------------------------------- Slawek · 2023-02-07 22:29 Hello, I made such an example: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit Unit1; {$mode objfpc}{$H+} interface uses  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls; type  TShowStatusEvent = procedure(Status, Task: String) of Object;   { TMyThread }   TMyThread = class(TThread)  private    fStatusText : string;    fTaskText : string;    FOnShowStatus: TShowStatusEvent;    procedure ShowStatus;  protected    procedure Execute; override;  public    constructor Create(CreateSuspended : boolean);    property OnShowStatus: TShowStatusEvent read FOnShowStatus write FOnShowStatus;  end;   { TForm1 }   TForm1 = class(TForm)    btStart: TButton;    btStop: TButton;    laTask: TLabel;    laStatus: TLabel;    procedure btStartClick(Sender: TObject);    procedure btStopClick(Sender: TObject);    procedure FormCreate(Sender: TObject);    procedure FormDestroy(Sender: TObject);  private    MyThread: TMyThread;    procedure ShowStatus(Status, Task: string);  public   end; var  Form1: TForm1; implementation {$R *.lfm} { TMyThread } procedure TMyThread.ShowStatus;begin  if Assigned(FOnShowStatus) then begin    FOnShowStatus(fStatusText, fTaskText);  end;end; procedure TMyThread.Execute;var i: Integer;begin  fStatusText := 'TMyThread Starting...';  Synchronize(@ShowStatus);  fStatusText := 'TMyThread Running...';  while (not Terminated) do begin //repeat all tasks    for i:= 1 to 9 do begin      if Terminated then Break; //abort      fTaskText:='Task no '+i.ToString;      sleep(500);      if not Terminated then        Synchronize(@Showstatus);    end;  end;end; constructor TMyThread.Create(CreateSuspended: boolean);begin  inherited Create(CreateSuspended);end; { TForm1 } procedure TForm1.btStartClick(Sender: TObject);begin  btStart.Enabled:=False;  laStatus.Caption:='Started';  MyThread.Start;  btStop.Enabled:=True;end; procedure TForm1.btStopClick(Sender: TObject);begin  btStop.Enabled:=False;  MyThread.Terminate;  MyThread.WaitFor;  laStatus.Caption:='Terminated';  btStart.Enabled:=True;end; procedure TForm1.FormCreate(Sender: TObject);begin  btStop.Enabled:=False;  MyThread := TMyThread.Create(true);  MyThread.FreeOnTerminate := False;  MyThread.OnShowStatus := @ShowStatus;end; procedure TForm1.FormDestroy(Sender: TObject);begin  if Assigned(MyThread) then begin    MyThread.Terminate;    MyThread.WaitFor;  end;end; procedure TForm1.ShowStatus(Status, Task: string);begin  laStatus.Caption := Status;  laTask.Caption := Task;end; end.  I can start and stop it, but when I want to start it again, the tasks in the thread are not executed. Even "TMyThread Starting..." is not displayed. Should the thread stop be done differently in this example? Of course, I'm not talking about a pause. I want to stop the thread completely and then start it again. Unfortunately, I don't know why it doesn't start again. If I move the thread creation (marked fragment) to btStartClick then everything works. Can a created thread be run only once? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TForm1.btStartClick(Sender: TObject);begin  btStart.Enabled:=False;  MyThread := TMyThread.Create(true);  MyThread.FreeOnTerminate := True;  MyThread.OnShowStatus := @ShowStatus;  laStatus.Caption:='Started';  MyThread.Start;  btStop.Enabled:=True;end; ---------------------------------------------------------------------- cdbc · 2023-02-08 12:36 Hi QuoteCan a created thread be run only once?Yes. When you exit the Execute method, the thread is done. I.e. you must create it anew. Try to follow TThread in the source, how it gets created etc... Then you'll see that, Execute IS the ThreadFunc. TThread just adds a lot of clever stuff to the mix  Hth - Regards Benny ---------------------------------------------------------------------- Slawek · 2023-02-08 13:06 Quote from: cdbc on February 08, 2023, 01:36:08 pmHi QuoteCan a created thread be run only once?Yes. When you exit the Execute method, the thread is done. I.e. you must create it anew. That explains a lot to me. Thank you for your response. Quote from: cdbc on February 08, 2023, 01:36:08 pmTry to follow TThread in the source, how it gets created etc... Then you'll see that, Execute IS the ThreadFunc. I can't find it, but I believe you it is. ---------------------------------------------------------------------- cdbc · 2023-02-08 18:54 Hi Slawek In the source editor, [ctrl + left-click] on TThread, editor will jump to its implementation, then [ctrl + shift + down arrow] will jump from interface to implementation... Try to follow TThread.Create(...), then you'll see "SysCreate(CreateSuspended, StackSize);" at the end, ctrl- click on that and then ctrl-shift-down... There's some pretty clever stuff in there  If you must, you can google for "sleeping threads", OmniThreadLibrary https://github.com/gabr42/OmniThreadLibrary implements them and I think EZThreads does too... https://github.com/mr-highball/ezthreads ... or you can roll your own  Have fun - Regards Benny ---------------------------------------------------------------------- Slawek · 2023-02-08 21:32 Thank you very much for this information and links. I'm just getting started with threads. This is not an easy topic. I need to calmly analyze, test and sort everything out in my head  There is quite a lot of knowledge about threads on the internet and on this forum, but so far it seems chaotic to me. ---------------------------------------------------------------------- jamie · 2023-02-08 23:54 Maybe it makes no difference here however, you did not specify to OVERRIDE the constructor in the base thread class. Constructor Create(.....) override; <<<< Scrub that! ---------------------------------------------------------------------- jamie · 2023-02-09 00:31 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i unit Unit1; {$mode objfpc}{$H+} interface uses  Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, Grids; type TMyThread = Class(TTHread)   Constructor Create(CreateSuspended:Boolean;Const StackSize:SizeUint=DefaultStackSize);Virtual;   Procedure Execute; Override; end;   { TForm1 }   TForm1 = class(TForm)    Button1: TButton;    Button2: TButton;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);    procedure FormCreate(Sender: TObject);    procedure FormDestroy(Sender: TObject);  private   public    MyTh:TMyThread;  end; var  Form1: TForm1; implementation {$R *.lfm}Procedure TMyThread.Execute;Var  T,U:Int64;Begin  T:=0;  While Not Terminated do    Begin     U:= GetTickCount64;     if Abs(U-T) > 2000 THen       Begin         T := U;         Beep;       end;    end;end; Constructor TMyThread.Create(CreateSuspended:Boolean;Const StackSize:SizeUint=DefaultStackSize);Begin  inherited Create(CreateSuspended,StackSize);end; { TForm1 } procedure TForm1.Button1Click(Sender: TObject);begin MyTh.Start;end; procedure TForm1.Button2Click(Sender: TObject);begin Myth.Suspend;end; procedure TForm1.FormCreate(Sender: TObject);begin  MyTh := TMythread.Create(True);  MyTh.FreeOnTerminate := False;end; procedure TForm1.FormDestroy(Sender: TObject);begin  MyTh.Terminate;  MyTh.Free;end; end.   This works for me. You can also do this in the Execute Method by using a flag. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Procedure TMyThread.Execute;Var  T,U:Int64;Begin  T:=0;  While Not Terminated do   If Not Paused Then    Begin     U:= GetTickCount64;     if Abs(U-T) > 2000 THen       Begin         T := U;         Beep;       end;    end;end;                     So you get the thread started and simply toggle the PAUSE boolean which is something you add to your Thread class in the public section.  This way the thread is always running and you can also yield to other threads using that check point..   If Not Terminated Then      If Not Paused then           Begin              .....           End Else Yield; etc.. ---------------------------------------------------------------------- Slawek · 2023-02-09 15:21 Thank you Jamie. Your explanation of this example seems understandable to me. I'll test it tonight