a simple example of a multithreaded Delphi program. In this example, we'll create a Delphi application with two threads,

each printing messages to the console.

delphi
program MultithreadedApp;neema blog 18

{$APPTYPE CONSOLE}

uses
  SysUtils, Classes, Windows;

type
  TMyThread = class(TThread)
  protected
    procedure Execute; override;
  end;

procedure TMyThread.Execute;
begin
  // Print messages from each thread
  while not Terminated do
  begin
    Writeln('Thread ID: ', GetCurrentThreadId, ' is running.');
    Sleep(1000); // Sleep for 1 second
  end;
end;

var
  Thread1, Thread2: TMyThread;
begin
  try
    // Create two threads
    Thread1 := TMyThread.Create(False);
    Thread2 := TMyThread.Create(False);

    // Wait for threads to finish
    Thread1.WaitFor;
    Thread2.WaitFor;
  except
    on E: Exception do
      Writeln('Exception: ', E.ClassName, ': ', E.Message);
  end;
end.



In this code:

TMyThread is a custom thread class inherited from TThread. The Execute method is overridden to define the code that runs in the thread. Each thread prints its ID to the console every second using GetCurrentThreadId and Writeln. We create two instances of TMyThread, Thread1 and Thread2, passing False to the constructor to indicate that the threads should start running immediately. Finally, we call WaitFor on both threads to wait for them to finish executing.



But what multithread Program?

We use cookies

We use cookies on our website. Some of them are essential for the operation of the site, while others help us to improve this site and the user experience (tracking cookies). You can decide for yourself whether you want to allow cookies or not. Please note that if you reject them, you may not be able to use all the functionalities of the site.