How to stop a thread? lazarus / 21-General ---------------------------------------------------------------------- Ramses · 2021-02-02 20:35 Hi everybody! Im working on a raspberry board and im actually trying to run a process in a thread, it is working very well, but i want to be able to stop the thread with a button, and i dont figure out how to do this.. here is my code: 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, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type{ TForm1 }  TForm1 = class(TForm)    Button1: TButton;    Button2: TButton;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);  private   public   end;    function MyThread(aPtr: Pointer): PtrInt; var  Form1: TForm1; implementation function MyThread(aPtr: Pointer): PtrInt;begin  Sleep(5000); // i can replace it with any code i want in my thread  Form1.Button1.Enabled:=True;end; {$R *.lfm} { TForm1 } procedure TForm1.Button1Click(Sender: TObject);begin  Button1.Enabled:=False;  BeginThread(@MyThread);end; procedure TForm1.Button2Click(Sender: TObject);begin  EndThread(@MyThread); // <-- Its not working!end; end.  How can i stop the thread by pressing the "button2"? Thanks! ---------------------------------------------------------------------- Peter H · 2021-02-02 20:57 It is always the best, if the thread polls a flag and self-suspends or self-terminates. If the thread does blocking IO, this is not possible and, dependant from the OS "EndThread" possibly does not work. If the thread is killed forcefully while in an unknown state the result is application dependent and hard to predict or OS-dependant the killing can fail. ---------------------------------------------------------------------- AlexTP · 2021-02-02 21:10 Set the global flag to True in the main thread. Thread-2 must check it and do "exit". ---------------------------------------------------------------------- marcov · 2021-02-02 21:57 Replace the sleep by teventobject.waitfor. Then signal the object to break the lock. For other calls, try to find a version that unblocks using a TEvent. On *nix, sometimes fpselect() can be used. ---------------------------------------------------------------------- Ramses · 2021-02-03 00:04 Quote from: Peter H on February 02, 2021, 09:57:34 pmIt is always the best, if the thread polls a flag and self-suspends or self-terminates. If the thread does blocking IO, this is not possible and, dependant from the OS "EndThread" possibly does not work. If the thread is killed forcefully while in an unknown state the result is application dependent and hard to predict or OS-dependant the killing can fail. QuoteSet the global flag to True in the main thread. Thread-2 must check it and do "exit". im a beginner with lazarus, so for sure i ask question that are "basic"for other peoples... well i tried to set a variable to stop the thread, but it doest work too... 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, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls; type{ TForm1 }  TForm1 = class(TForm)    Button1: TButton;    Button2: TButton;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);  private   public   end;    function MyThread(aPtr: Pointer): PtrInt; var  Form1: TForm1;  threadIsRunning: Boolean = true; implementation function MyThread(aPtr: Pointer): PtrInt;begin   while threadIsRunning do begin      Sleep(5000); // i can replace it with any code i want in my thread      end;  Form1.Button1.Enabled:=True;end; {$R *.lfm} { TForm1 } procedure TForm1.Button1Click(Sender: TObject);begin  Button1.Enabled:=False;  threadIsRunning := true;  BeginThread(@MyThread);end; procedure TForm1.Button2Click(Sender: TObject);begin threadIsRunning := false;end; end.  maybe someont can give me an exemple code that can stop my thread the right way? ---------------------------------------------------------------------- Ramses · 2021-02-03 00:13 Quote from: marcov on February 02, 2021, 10:57:54 pmReplace the sleep by teventobject.waitfor. Then signal the object to break the lock. The "sleep" that i put there is just an exemple, so what i want is to stop the thread itself, without changing this line: that way i will be able to replace the "sleep" by anything i want later when my stop button will work ---------------------------------------------------------------------- trev · 2021-02-03 01:58 Define "but it doest work too" - what doesn't work? 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 function MyThread(aPtr: Pointer): PtrInt;begin  WriteLn('Thread: ' + myThread.ToString);   while threadIsRunning do    begin      WriteLn('Starting sleep...');      sleep(2000);      WriteLn('Ending sleep!');    end;   Form1.Button1.Enabled := True;  WriteLn('Thread ' + myThread.ToString + ' exiting');end; Works for me: Code: Text  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i Thread: 123145540231168Starting sleep...Ending sleep!Starting sleep...Ending sleep!Starting sleep...Ending sleep!Starting sleep...Ending sleep!Thread 123145540231168 exiting As mentioned, sleep() is blocking so you have to wait for it to expire before the thread exits. ---------------------------------------------------------------------- Ramses · 2021-02-03 02:06 Quote from: trev on February 03, 2021, 02:58:45 amDefine "but it doest work too" - what doesn't work? Thanks for your reply The thread dosent stop when i press the button, it stop only after the sleep ended... For exemple, if the sleep is very long, i have to wait until the sleep is end. (like the 1 minute sleep in the exemple below) I want the thread to stop as soon as i press the button. so i want to "kill" the thread as soon as the button is pressed is there any way to do that? 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 function MyThread(aPtr: Pointer): PtrInt;begin   while threadIsRunning do begin      Sleep(60000); // i can replace it with any code i want in my thread      end;  Form1.Button1.Enabled:=True;end; ---------------------------------------------------------------------- PascalDragon · 2021-02-03 08:07 Quote from: Ramses on February 03, 2021, 03:06:11 amI want the thread to stop as soon as i press the button. so i want to "kill" the thread as soon as the button is pressed is there any way to do that? That is simply not how things are done. While in theory it's possible to kill a thread inside ones own process it's definitely not advised as the thread might be holding some lock or might be inside some other operation that can't easily be undone without leaving the state in disarray. Thus it's generally advised to do this cooperatively, thus the thread needs to regularly check whether it should terminate and then leave its thread function. When you have some long running code inside your thread loop you should check between various parts as well (for example if you have steps "fetch data" and "process data" you should check between those two as well). ---------------------------------------------------------------------- Ramses · 2021-02-03 11:13 Quote from: PascalDragon on February 03, 2021, 09:07:22 am When you have some long running code inside your thread loop you should check between various parts as well  Thanks for your reply, but sometime its not really possible to separate the code in multiple part... Let say for example that i need to play a long song, or a tone on my speaker (like in the example below) if i cut the tone in different part, the sound will not be continuous on the speaker and its not what i want. but i need to be able to stop the tone when i press a button... 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 function MyThread(aPtr: Pointer): PtrInt;begin   while threadIsRunning do begin      ALSAbeep(40, 60000, 100, true,2, true); // this other exemple generate a continuous tone for 60 seconds      end;  Form1.Button1.Enabled:=True;end;  So i understand what you told me, and if there is not advised to do that, i will try to found another solution... ---------------------------------------------------------------------- 440bx · 2021-02-03 11:46 Quote from: Ramses on February 03, 2021, 12:13:19 pmLet say for example that i need to play a long song, or a tone on my speaker (like in the example below) if i cut the tone in different part, the sound will not be continuous on the speaker and its not what i want. but i need to be able to stop the tone when i press a button...The button you're mentioning should set a flag indicating to the thread that is producing the sound to end.  Checking the flag introduces a delay that is in the order of a few _nanoseconds_, this makes it extremely unlikely that any discontinuity in the sound could be humanly perceived.  (In today's typical machine - not a high end machine - a simple IF statement executes roughly a billion times per second.) 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 if SomeFlag then EndThread(ThreadExitCode);This IF statement executes roughly a billion times per second. Another possibility is to use SuspendThread() and ResumeThread() along with a "state" of what the resumed thread is supposed to play. HTH. ---------------------------------------------------------------------- MarkMLl · 2021-02-03 11:51 Quote from: Ramses on February 03, 2021, 12:13:19 pmQuote from: PascalDragon on February 03, 2021, 09:07:22 am When you have some long running code inside your thread loop you should check between various parts as well  Thanks for your reply, but sometime its not really possible to separate the code in multiple part... Let say for example that i need to play a long song, or a tone on my speaker (like in the example below) if i cut the tone in different part, the sound will not be continuous on the speaker and its not what i want. but i need to be able to stop the tone when i press a button... 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 function MyThread(aPtr: Pointer): PtrInt;begin   while threadIsRunning do begin      ALSAbeep(40, 60000, 100, true,2, true); // this other exemple generate a continuous tone for 60 seconds      end;  Form1.Button1.Enabled:=True;end;  So i understand what you told me, and if there is not advised to do that, i will try to found another solution... I've already told you how to fix that. You make sure that your AlsaBeep() is broken up internally into chunks of say 100 mSec each. See for example BeepPcm() in https://github.com/MarkMLl/asound/blob/main/examples/alsapcmdemo.pas, and where it's calling Application.ProcessMessages replace that with polling a termination flag. MarkMLl ---------------------------------------------------------------------- Ramses · 2021-02-03 14:28 Thanks for all your reply! In fact the "alsa_beep" is just an exemple: i started this discussion to know if there was an easy way to stop/kill a thread only with a command like "endthread(mythread)" But according to the answer, i understand that is not recommended to do that, and the correct way is to set code inside the thread to verify if its the time to stop... So i got my answer: now i will work that way instead of just trying to kill the thread Thanks to everybody who help me in this discussion!