Advertisement
Guest User

threadtest.pas

a guest
Aug 11th, 2019
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 1.61 KB | None | 0 0
  1. program threadtest;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. uses
  6.   //{$IFDEF UNIX}{$IFDEF UseCThreads}
  7.   cthreads, cmem,
  8.   //{$ENDIF}{$ENDIF}
  9.   Classes, // TThread
  10.   SysUtils;// Format
  11.  
  12. type
  13.   { TMyThread }
  14.   TMyThread = class (TThread)
  15.   private
  16.     fCount: word;
  17.     fID: word;
  18.     procedure WriteSync;
  19.   protected
  20.     procedure Execute; override;
  21.   public
  22.     constructor Create(aCreateSuspended: boolean; aID, aCountdownFrom: word);
  23.   end;
  24.  
  25. constructor TMyThread.Create(aCreateSuspended: boolean; aID,
  26.   aCountdownFrom: word);
  27. begin
  28.   fID:= aID;
  29.   fCount := aCountdownFrom;
  30.   inherited Create(aCreateSuspended);
  31. end;
  32.  
  33. procedure TMyThread.WriteSync;
  34. begin
  35.   WriteLn(Format('Thread #%0.4d at count %0.3d', [fID, fCount]));
  36. end;
  37.  
  38. procedure TMyThread.Execute;
  39. begin
  40.   while not (terminated) and (fCount <> 0) do
  41.   begin
  42.     Synchronize(@WriteSync);
  43.     Dec(fCount);
  44.   end;
  45. end;
  46.  
  47. var
  48.   Threads: array of TMyThread;
  49.   i, countdownFrom: word;
  50.  
  51. function ThreadsFinished: boolean;
  52. begin
  53.   Result := True;
  54.   for i:= 0 to High(Threads) do
  55.   begin
  56.     Result := Threads[i].Finished and Result;
  57.   end;
  58. end;
  59.  
  60. begin
  61.   WriteLn('Randomizing');
  62.   Randomize;
  63.   SetLength(Threads, Random(1024));
  64.   WriteLn('Thread count ', Length(Threads));
  65.   for i:= 0 to High(Threads) do
  66.   begin
  67.     countdownFrom:= Random(128);
  68.     WriteLn('Making thread #', i, ' with count ', countdownFrom);
  69.     Threads[i]:=TMyThread.Create(false, i, countdownFrom);
  70.     Threads[i].Start();
  71.   end;
  72.   while not ThreadsFinished do
  73.   begin
  74.     CheckSynchronize();
  75.   end;
  76.   for i:= 0 to High(Threads) do
  77.     FreeAndNil(Threads[i])
  78. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement