In Delphi, you can use various synchronization mechanisms to allow communication between two threads. One common approach is to use a thread-safe queue or an event to pass messages between threads. Below is an example using a thread-safe queue to communicate between two threads.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
unit ThreadCommunication; interface uses Classes, SysUtils, Generics.Collections, Windows; type TMessageThread = class(TThread) private FMessageQueue: TThreadedQueue<string>; protected procedure Execute; override; public constructor Create; destructor Destroy; override; procedure SendMessage(const Msg: string); end; implementation { TMessageThread } constructor TMessageThread.Create; begin inherited Create(False); FreeOnTerminate := True; FMessageQueue := TThreadedQueue<string>.Create; end; destructor TMessageThread.Destroy; begin FMessageQueue.Free; inherited Destroy; end; procedure TMessageThread.Execute; var Msg: string; begin while not Terminated do begin if FMessageQueue.PopItem(Msg) then begin // Process the received message // … // For demonstration, print the message to the console Writeln(Format(‘Thread %d received message: %s’, [GetCurrentThreadId, Msg])); end; Sleep(10); // Sleep to avoid tight loop end; end; procedure TMessageThread.SendMessage(const Msg: string); begin FMessageQueue.PushItem(Msg); end; end. |
In this example, TMessageThread
is a thread class that listens for messages in a loop. The SendMessage
method is used to send messages to the thread.
To use this thread, you can create an instance of TMessageThread
in your main form or unit:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
unit MainForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ThreadCommunication; type TForm1 = class(TForm) Button1: TButton; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); private MessageThread: TMessageThread; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.FormCreate(Sender: TObject); begin MessageThread := TMessageThread.Create; end; procedure TForm1.FormDestroy(Sender: TObject); begin MessageThread.Terminate; MessageThread.WaitFor; MessageThread.Free; end; procedure TForm1.Button1Click(Sender: TObject); begin // Send a message to the thread when the button is clicked MessageThread.SendMessage(‘Hello from main thread!’); end; end. |
In this example, when you click the button, it sends a message to the TMessageThread
, and the thread processes the received message. Note that you should be cautious with how you handle synchronization between threads to avoid race conditions and deadlocks.
Leave a Reply