testthreadpool.pp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. {$mode objfpc}
  2. {$h+}
  3. program testthreadpool;
  4. uses {$ifdef unix}cThreads, {$ENDIF} sysutils, fpthreadpool;
  5. type
  6. { TMyTask }
  7. TMyTask = Class(TThreadPoolTask)
  8. FID : Integer;
  9. destructor destroy; override;
  10. procedure DoQueued; override;
  11. Procedure DoExecute; override;
  12. Constructor Create(aID : Integer);
  13. Function ToString : string; override;
  14. end;
  15. { TMyTask }
  16. destructor TMyTask.destroy;
  17. begin
  18. Writeln(FID,': Destroy : ',ToString);
  19. Flush(Output);
  20. inherited destroy;
  21. end;
  22. procedure TMyTask.DoQueued;
  23. begin
  24. Writeln(FID,': Queued : ',ToString);
  25. Flush(Output);
  26. inherited DoQueued;
  27. end;
  28. procedure TMyTask.DoExecute;
  29. Var
  30. I,Sec: Integer;
  31. begin
  32. Sec:=3+Random(3);
  33. Writeln(FID,': Task ',ToString,' waiting ',Sec,' seconds.');
  34. Flush(Output);
  35. I:=1;
  36. While (I<=Sec) and Not Terminated do
  37. begin
  38. Sleep(Sec);
  39. Inc(I);
  40. end;
  41. Writeln(FID,': Task ',ToString,' done waiting (',Sec,' seconds). ');
  42. Flush(Output);
  43. end;
  44. constructor TMyTask.Create(aID: Integer);
  45. begin
  46. FID:=AID;
  47. end;
  48. function TMyTask.ToString: string;
  49. begin
  50. Result:=ClassName+' '+HexStr(Self)+' : '+IntToStr(FID);
  51. end;
  52. procedure RunTest(aPool : TFPCustomSimpleThreadPool);
  53. Var
  54. I : Integer;
  55. T : TMyTask;
  56. begin
  57. For I:=1 to 200 do
  58. begin
  59. T:=TMyTask.Create(I);
  60. if not aPool.AddTask(T) then
  61. begin
  62. Writeln('Task not accepted, freeing');
  63. Flush(Output);
  64. T.Free;
  65. end;
  66. end;
  67. end;
  68. Var
  69. MyPool : TFPSimpleThreadPool;
  70. begin
  71. MyPool:=TFPSimpleThreadPool.Create;
  72. try
  73. MyPool.AddTimeout:=40;
  74. MyPool.AutoCheckQueuedTasks:=True;
  75. // RunTest(MyPool);
  76. RunTest(TFPSimpleThreadPool.Instance);
  77. finally
  78. MyPool.Free;
  79. end;
  80. end.