Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program threadtest;
- {$mode objfpc}{$H+}
- uses
- //{$IFDEF UNIX}{$IFDEF UseCThreads}
- cthreads, cmem,
- //{$ENDIF}{$ENDIF}
- Classes, // TThread
- SysUtils;// Format
- type
- { TMyThread }
- TMyThread = class (TThread)
- private
- fCount: word;
- fID: word;
- procedure WriteSync;
- protected
- procedure Execute; override;
- public
- constructor Create(aCreateSuspended: boolean; aID, aCountdownFrom: word);
- end;
- constructor TMyThread.Create(aCreateSuspended: boolean; aID,
- aCountdownFrom: word);
- begin
- fID:= aID;
- fCount := aCountdownFrom;
- inherited Create(aCreateSuspended);
- end;
- procedure TMyThread.WriteSync;
- begin
- WriteLn(Format('Thread #%0.4d at count %0.3d', [fID, fCount]));
- end;
- procedure TMyThread.Execute;
- begin
- while not (terminated) and (fCount <> 0) do
- begin
- Synchronize(@WriteSync);
- Dec(fCount);
- end;
- end;
- var
- Threads: array of TMyThread;
- i, countdownFrom: word;
- function ThreadsFinished: boolean;
- begin
- Result := True;
- for i:= 0 to High(Threads) do
- begin
- Result := Threads[i].Finished and Result;
- end;
- end;
- begin
- WriteLn('Randomizing');
- Randomize;
- SetLength(Threads, Random(1024));
- WriteLn('Thread count ', Length(Threads));
- for i:= 0 to High(Threads) do
- begin
- countdownFrom:= Random(128);
- WriteLn('Making thread #', i, ' with count ', countdownFrom);
- Threads[i]:=TMyThread.Create(false, i, countdownFrom);
- Threads[i].Start();
- end;
- while not ThreadsFinished do
- begin
- CheckSynchronize();
- end;
- for i:= 0 to High(Threads) do
- FreeAndNil(Threads[i])
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement