Mega Code Archive

 
Categories / Delphi / Examples
 

Thread demo

For those of you who haven't been into Thread-programming, maybe this simple demo would be of interest: The program creates ten parallell threads, each thread is associated with a progressbar, which is updated randomly. When the Thread is done it's reported to a memo. You can download the pas- and dfm-file here: unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; type TProgressThread = class(TThread) private fRandomNo: Integer; fThreadNo: Integer; fProgress: Integer; fDone: Boolean; protected procedure Execute; override; procedure ShowProgress; end; TForm1 = class(TForm) Button1: TButton; ProgressBar1: TProgressBar; ProgressBar2: TProgressBar; ProgressBar3: TProgressBar; ProgressBar4: TProgressBar; ProgressBar5: TProgressBar; ProgressBar6: TProgressBar; ProgressBar7: TProgressBar; ProgressBar8: TProgressBar; ProgressBar9: TProgressBar; ProgressBar10: TProgressBar; Memo1: TMemo; procedure Button1Click(Sender: TObject); private ProgressThread: TProgressThread; { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); var n: Integer; begin Randomize; Memo1.Clear; // Create 10 Threads, give them a random no. and start them for n:= 1 to 10 do begin ProgressThread:= TProgressThread.Create(true); ProgressThread.FreeOnTerminate:= true; ProgressThread.fThreadNo:= n; ProgressThread.fRandomNo:= Random(100); ProgressThread.FProgress:= 0; ProgressThread.fDone:= false; // Start the Thread ProgressThread.Resume; end; end; { TProgressThread } procedure TProgressThread.Execute; begin repeat // Compare Threads RandomNo with a RandomNo generated each time looped // One chance of 100 000 that fProgress will be increased if fRandomNo = Random(100000) then begin if fProgress < 100 then begin Inc(fProgress); if fProgress = 100 then fDone:= true; // Update ProgressBar Synchronize(ShowProgress); end; end; until fDone; end; procedure TProgressThread.ShowProgress; begin // Update the ProgressBar associated with the Thread case fThreadNo of 1: Form1.ProgressBar1.Position:= fProgress; 2: Form1.ProgressBar2.Position:= fProgress; 3: Form1.ProgressBar3.Position:= fProgress; 4: Form1.ProgressBar4.Position:= fProgress; 5: Form1.ProgressBar5.Position:= fProgress; 6: Form1.ProgressBar6.Position:= fProgress; 7: Form1.ProgressBar7.Position:= fProgress; 8: Form1.ProgressBar8.Position:= fProgress; 9: Form1.ProgressBar9.Position:= fProgress; 10: Form1.ProgressBar10.Position:= fProgress; end; // Write to Memo if Done if fDone then Form1.Memo1.Lines.Add('Thread No: ' + IntToStr(fThreadNo) + ' terminated.'); end; end.