Multithread example that can access GUI lazarus / 61-Beginners ---------------------------------------------------------------------- Trenatos · 2015-08-11 14:23 I'm kicking off process and it's working great, the problem is that it of course locks up the GUI. I'm trying to figure out how to do multi-threading so that 1. running processes won't lock up GUI, and 2. so I can run multiple processes. I found examples online, but haven't been able to get them working. Can someone point me to a decent source with example, or write up a small example of multi-thread that interacts with the GUI? ---------------------------------------------------------------------- HeavyUser · 2015-08-11 14:31 Quote from: Trenatos on August 11, 2015, 04:23:05 pmI'm kicking off process and it's working great, the problem is that it of course locks up the GUI. I'm trying to figure out how to do multi-threading so that 1. running processes won't lock up GUI, and 2. so I can run multiple processes. I found examples online, but haven't been able to get them working. What did you try and why you can't use it? Quote from: Trenatos on August 11, 2015, 04:23:05 pmCan someone point me to a decent source with example, or write up a small example of multi-thread that interacts with the GUI? No! Single thread can access the GUI and that is the main thread only. Forget about refreshing the gui from threads it will never going to work. Decouple the data from the gui make the data structures thread safe inform the gui for changes. Thats it the gui will refresh it self when it has time as long as it knows that the data have changed. ---------------------------------------------------------------------- eny · 2015-08-11 14:49 Since you have read this: http://wiki.lazarus.freepascal.org/Multithreaded_Application_Tutorial, what questions do you still have? ---------------------------------------------------------------------- Trenatos · 2015-08-11 15:23 Plenty of questions but I'm starting simple. I got this working:  http://forum.codecall.net/topic/70827-very- simple-multithreading/ I'm trying to modify it to update a label. I've added a global variable, gTextString I'm updating the label in the start button. StartBeeping;   while true do   begin     theLabel.caption := gTextString;     Application.ProcessMessages;     if uStopBeeping then Exit;   end; If I set the variable to some text in the thread, it works, but if I do TimeToStr(Time) in the thread, I get a SigSegv, but not if I do it in the button handler. ---------------------------------------------------------------------- fpcoder · 2015-08-11 15:24 Synchronize and Queue are routines for updating the GUI from threads. Check this discussion for a demo that might be useful: http://forum.lazarus.freepascal.org/index.php/topic,26992.msg166744.ht ml#msg166744 Callbacks, methodpointers, dispatchmethods and event properties are useful terms when doing GUI <-> thread communiction. They are all part of the example above and its easier to actually do it than to describe. If I remember right, these are the steps in the demo: First create a method in the form unit that updates the form when called.Define a method type for the thread. (procedure of object)Declare a method pointer variable of this type in your derived thread class Create a Dispatch method in the derived thread class Create an event property in the derived thread class Assign the main form callback method to the threads event property For example in the threads execute method, call synchronize on the dispatch method and your GUI will be updated. ---------------------------------------------------------------------- derek.john.evans · 2015-08-11 16:06 Thread coding is somewhat tricky. Every time I code some, I seem to use a slightly different scheme. In the past Ive hard connected threads to GUI with pointers to controls. This meant, a GUI element couldn't deleted itself, until after the thread was terminated. Which, meant, the GUI elements needed pointers to threads, which meant threads couldn't freeonterminate, so I ended up implementing all these callbacks, bla bla bla. All because I used pointers to GUI elements. So, now I don't. I send the thread the component name, which it then has to find. If it doesn't, it terminates and free's. Which means, the GUI doesn't need to know about the threads. You can just free a GUI control without issue. With that idea, I coded this 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 type   TProcessThread = class(TThread)  strict private    FExecutable, FParameters, FLine, FSynEditName: String;  protected    procedure Execute; override;    procedure SynchronizeWriteLine;  public    constructor Create(const AExecuteable, AParameters, ASynEditName: String);  end; constructor TProcessThread.Create(const AExecuteable, AParameters, ASynEditName: String);begin  FExecutable := AExecuteable;  FParameters := AParameters;  FSynEditName := ASynEditName;  FreeOnTerminate := True;  inherited Create(False);end; procedure TProcessThread.SynchronizeWriteLine;var  LLastLine: String;  LSynEdit: TSynEdit;begin  if not Terminated then  begin    try      LSynEdit := Application.MainForm.FindComponent(FSynEditName) as TSynEdit;      if not Assigned(LSynEdit) then      begin        Terminate;      end else begin        with LSynEdit.Lines do        begin          BeginUpdate;          try            if Count = 0 then            begin              LLastLine := EmptyStr;            end else begin            LLastLine := Strings[Count - 1];              Delete(Count - 1);            end;            AddText(LLastLine + FLine + LineEnding);            while Count > 500 do            begin            Delete(0);            end;          finally            EndUpdate;          end;        end;        LSynEdit.CaretY := MaxInt;        Application.ProcessMessages;      end;    except      Terminate;    end;  end;end; procedure TProcessThread.Execute;   function LStreamReadChunk(const AStream: TStream): String;  var    LBuffer: array[byte] of Char;  begin    LBuffer[0] := #0;    SetString(Result, LBuffer, AStream.Read(LBuffer, SizeOf(LBuffer)));  end; var  LProcess: TProcess;begin  try    LProcess := TProcess.Create(nil);    try      LProcess.Options := LProcess.Options + [poUsePipes, poStderrToOutPut];      LProcess.ShowWindow := swoHIDE;      LProcess.Executable := FExecutable;      LProcess.Parameters.Text := FParameters;      LProcess.Execute;      while not Terminated and LProcess.Running do      begin        while not Terminated and LProcess.Running and (LProcess.Output.NumBytesAvailable = 0) do      begin          Sleep(400);        end;        FLine := LStreamReadChunk(LProcess.Output);        Synchronize(@SynchronizeWriteLine);      end;      repeat        FLine := LStreamReadChunk(LProcess.Output);        Synchronize(@SynchronizeWriteLine);      until Terminated or (LProcess.Output.NumBytesAvailable = 0);    finally      FreeAndNil(LProcess);    end;  except    on E: Exception do    begin    FLine := E.Message + LineEnding;      Synchronize(@SynchronizeWriteLine);    end;  end;  FLine := '**** PROCESS COMPLETE ****' + LineEnding;  Synchronize(@SynchronizeWriteLine);end; With two helper functions: 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 RunExecutable(const AExecutable, AParameters: String; const ASynEdit: TSynEdit);begin  TProcessThread.Create(AExecutable, AParameters, ASynEdit.Name);end; procedure RunDosCommand(const ACommand: String; const ASynEdit: TSynEdit);begin  RunExecutable('cmd', '/C'#13 + ACommand, ASynEdit);end; With some test examples: 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   RunDosCommand('dir /s C:\WINDOWS', SynEdit1);  RunExecutable('java', '-help', SynEdit2);  RunDosCommand('dir /s C:\', SynEdit3);   NOTE: The thread looks for the component name in the main form, so this only works for TSynEdit controls that are on the main form. ---------------------------------------------------------------------- Trenatos · 2015-08-11 17:49 derek, that is a beautiful example, it works perfectly! I'll dig into it and see if I can adapt it to do what I need the final project to do ---------------------------------------------------------------------- derek.john.evans · 2015-08-11 18:13 Quote from: Trenatos on August 11, 2015, 07:49:05 pmderek, that is a beautiful example, it works perfectly! I'll dig into it and see if I can adapt it to do what I need the final project to do Cool. As a tip, when you go to upscale that idea, you will most likely use a TPageControl. Therefore, each TSynEdit will be dynamically created inside TTabSheets. The TPageControl will own the TSynEdit's, so the FindComponent command needs to be changed to: Code: [Select]FormMain.PageControl.FindComponent(FSynEditName) as TSynEdit;  Each TSynEdit needs to have a new name, so, use a counter to create a new index for a name. EG: Code: [Select]procedure TFormMain.Button1Click(Sender: TObject); var   LSynEdit: TSynEdit;   LTabSheet: TTabSheet; begin   LTabSheet := PageControl.AddTabSheet;   LTabSheet.Caption := 'Console';   LSynEdit := TSynEdit.Create(PageControl);   LSynEdit.Name := 'SynEdit' + IntToStr(FSynEditCounter);   LSynEdit.Text := EmptyStr;   LSynEdit.Align := alClient;   LSynEdit.Parent := LTabSheet;   LTabSheet.Show;   Inc(FSynEditCounter);   RunDosCommand('dir /s C:\', LSynEdit); end;    Then if you have a 'stop process' button it just has todo this: Code: [Select]procedure TFormMain.Button2Click(Sender: TObject); begin   PageControl.ActivePage.Free; end;  And all is well in the world. ---------------------------------------------------------------------- Trenatos · 2015-08-11 18:26 I'm thinking of just using one synedit and a tab control, letting each process save to a variable somewhere, and update the synedit to display whatever process' tab is clicked on. That way I only need a single synedit, and all updates happen through the onclick on the tabcontrol. Not sure if that's easier or not, but it's a solution I've used before ---------------------------------------------------------------------- derek.john.evans · 2015-08-11 18:35 Maybe. The code I've written relies on the TStrings.AddText() which handles the the various CRLF/LFCR/LF/CR possibilities. Which means, you would still need a bunch of TStringList's. Which arn't components, so they cant be searched for via FindComponent(). So, by the time you write a TObjectList for the TStringList's, and copy the TStringList's into the one TSynEdit when clicking a tab, you might as well have multiple TSynEdit's ---------------------------------------------------------------------- Trenatos · 2015-08-11 21:14 I'm racing now, getting lots done in a short time. The problem I'm having right now is simple, I don't understand threads. As I kick off a thread, I need to save a reference to it so that I can later kill it through a button. I looked at your added code, but don't understand how the referencing would work. ---------------------------------------------------------------------- derek.john.evans · 2015-08-11 21:48 First up, you cant kill a thread. You can politely ask it to terminate, but then it is upto the thread whether it will or not. Hence, why in the TThread.Execute you check Terminated, to see if it should continue or not. Problem is, as soon as you think about the idea of calling TThread.Terminate, you can no longer use FreeOnTerminate, since, it is possible that the pointer to the thread is no longer valid. Unless, the thread has a callback system for when it terminates, or it has a pointer to the pointer of itself, which it can set to nil, which is a little dodgy if you ask me. It all gets very messy very quickly. So, how my code works is, the thread syncronizes with the main thread, and trys to find the GUI control it uses for display stuff. in this case, a TSynEdit control. If it isn't found, then the thread terminates itself. So, all you have todo is free the TSynEdit control. The thread will terminate when its ready todo so. Simple. **EDIT* You may want to terminate the thread without freeing the TSynEdit. So, use a flag in TSynEdit like Enabled. Set TSynEdit.Enabled := False. The thread can detect that and terminate itself, but, before it does, it should set TSynEdit.Enabled to True. (in the syncronized method) ---------------------------------------------------------------------- Trenatos · 2015-08-11 21:54 Aha, I see. That makes it a little more complicated, as it seems Java processes do not like to exit nicely. The simplest way I can think of is to send the ctrl + c combination, that will kill the process through its built-in functionality. Without doing that, the process just stays up and never terminates. ---------------------------------------------------------------------- derek.john.evans · 2015-08-11 21:57 Try putting this line in: Code: [Select]     LProcess.Terminate(-1); // NEW LINE: Unsure if the code will make a difference.           // NORMAL CODE FOLLOWS       repeat         FLine := LStreamReadChunk(LProcess.Output);         Synchronize(@SynchronizeWriteLine);       until Terminated or (LProcess.Output.NumBytesAvailable = 0); ---------------------------------------------------------------------- rvk · 2015-08-11 22:10 Quote from: derek.john.evans on August 11, 2015, 11:48:13 pmFirst up, you cant kill a thread. You can politely ask it to terminate, but then it is upto the thread whether it will or not. Uuh, how about KillThread? It calls TerminateThread in Windows. But you should never use it. Especially in these circumstances. Signaling the thread another way (like you showed) and letting it end on its own is always better than hard-killing the thread. But it is possible. ---------------------------------------------------------------------- derek.john.evans · 2015-08-11 22:21 Quote from: rvk on August 12, 2015, 12:10:09 amQuote from: derek.john.evans on August 11, 2015, 11:48:13 pmFirst up, you cant kill a thread. You can politely ask it to terminate, but then it is upto the thread whether it will or not. Uuh, how about KillThread? It calls TerminateThread in Windows. But you should never use it. Especially in these circumstances. Signaling the thread another way (like you showed) and letting it end on its own is always better than hard-killing the thread. But it is possible. Well, I'll be. Never seen KillThread. It maps to TerminateThread on Win32. But, yea, not good for the TThread/TProcess objects. ---------------------------------------------------------------------- rvk · 2015-08-11 22:28 Quote from: derek.john.evans on August 12, 2015, 12:21:48 amWell, I'll be. Never seen KillThread. It maps to TerminateThread on Win32. But, yea, not good for the TThread/TProcess objects. It might come in handy if your thread is stuck and doesn't want to end. (also should work cross platform) Code: [Select]//wait 6 seconds for thread to finish, if WaitForThreadTerminate(TestThread.handle,6000) <> 0 then   //didn't finish, lets kill it.   KillThread(TestThread.handle);    Code from here and here ---------------------------------------------------------------------- derek.john.evans · 2015-08-11 22:45 I think if it takes 6 seconds to terminate a thread, it might be time to terminate the program ---------------------------------------------------------------------- Leledumbo · 2015-08-12 10:37 Back to OP, see my projects: https://bitbucket.org/leledumbo/zita-aj-bridge-gui https://bitbucket.org/leledumbo/express Both are GUI wrappers over console apps. The first one keeps reading output as long as the underlying program runs. ---------------------------------------------------------------------- Trenatos · 2015-08-12 12:49 I got it working by using start.jar, which can send a stop signal to a jetty process. Score! Now all I need is to save the output into separate variables and display as needed, and this part is done ---------------------------------------------------------------------- taazz · 2015-08-12 13:02 Quote from: Trenatos on August 12, 2015, 02:49:22 pmI got it working by using start.jar, which can send a stop signal to a jetty process. Score! Now all I need is to save the output into separate variables and display as needed, and this part is done    you do know this is a pascal forum, right? Not a java one, correct? ---------------------------------------------------------------------- Trenatos · 2015-08-12 13:38 Whaaaaat? I had no idea. Yes, I do. I'm writing a Pascal (Lazarus) based software that will handle multiple instances of jetty servers with output handling, data evaluation, log handling, and more, all written in Pascal. Jetty runs on top of Java, thus all the java talk. Once started, the Jetty instance doesn't want to close nicely by any mean I've found through Pascal, but I DID manage to get the standard way of closing Jetty gracefully by using start.jar. How? Well, by kicking off a process that runs the start.jar file with the proper parameters, which connects to and tells the specific Jetty instance to shut down gracefully. Hope that clears things up.