forked from gabr42/OmniThreadLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OtlThreadPool.pas
1560 lines (1435 loc) · 56.6 KB
/
OtlThreadPool.pas
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///<summary>Thread pool. Part of the OmniThreadLibrary project.</summary>
///<author>Primoz Gabrijelcic</author>
///<license>
///This software is distributed under the BSD license.
///
///Copyright (c) 2011, Primoz Gabrijelcic
///All rights reserved.
///
///Redistribution and use in source and binary forms, with or without modification,
///are permitted provided that the following conditions are met:
///- Redistributions of source code must retain the above copyright notice, this
/// list of conditions and the following disclaimer.
///- Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///- The name of the Primoz Gabrijelcic may not be used to endorse or promote
/// products derived from this software without specific prior written permission.
///
///THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
///ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
///WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
///DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
///ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
///(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
///LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
///ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
///(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
///SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///</license>
///<remarks><para>
/// Home : http://www.omnithreadlibrary.com
/// Support : https://plus.google.com/communities/112307748950248514961
/// Author : Primoz Gabrijelcic
/// E-Mail : [email protected]
/// Blog : http://thedelphigeek.com
/// Contributors : GJ, Lee_Nover, Sean B. Durkin
/// Creation date : 2008-06-12
/// Last modification : 2015-10-04
/// Version : 2.12
/// </para><para>
/// History:
/// 2.12: 2015-10-04
/// - Imported mobile support by [Sean].
/// 2.11: 2015-09-07
/// - Setting MinWorkers property will start up idle worker threads if total number
/// of threads managed by the thread pool is lower than the new value.
/// 2.10: 2015-09-03
/// - Removed limitation on max 60 threads in a pool (faciliated by changes in
/// OtlTaskControl).
/// 2.09a: 2012-01-31
/// - More accurate CountQueued.
/// 2.09: 2011-11-08
/// - Adapted to OtlCommon 1.24.
/// 2.08: 2011-11-06
/// - Sets thread name to 'Idle thread worker' when a thread is idle.
/// 2.07: 2011-07-14
/// - Exceptions are no longer reported through the OnPoolWorkItemCompleted event.
/// 2.06: 2011-07-04
/// - Fixed task exception handling. Exceptions are now reported through the
/// OnPoolWorkItemCompleted event.
/// 2.05b: 2010-11-25
/// - Bug fixed: Thread pool was immediately closing unused threads if MaxExecuting
/// was set to -1.
/// 2.05a: 2010-07-19
/// - Works correctly if MaxExecuting is set to 0. Set MaxExecuting to -1 to allow
/// "infinite" number of execution threads.
/// - When MaxExecuting is changed, the code checks immediately if tasks from the
/// idle queue can now be activated.
/// 2.05: 2010-07-01
/// - Includes OTLOptions.inc.
/// 2.04a: 2010-06-06
/// - Modified patch from 2.04 so that it's actually working.
/// 2.04: 2010-05-30
/// - ThreadDataFactory can now accept either a function or a method.
/// 2.03c: 2010-01-09
/// - Fixed CancelAll.
/// - Can be compiled with /dLogThreadPool.
/// 2.03b: 2009-12-12
/// - Fixed exception handling for silent exceptions.
/// 2.03a: 2009-11-17
/// - Task worker must not depend on monitor to be assigned.
/// - SetMonitor must be synchronous.
/// 2.02: 2009-11-13
/// - D2010 compatibility changes.
/// 2.01b: 2009-03-03
/// - Bug fixed: TOTPWorkerThread.Create was not waiting on the worker object to
/// initialize.
/// 2.01a: 2009-02-09
/// - Removed critical section added in 2.0b - it is not needed as the
/// IOmniTaskControl.Invoke is thread-safe.
/// 2.01: 2009-02-08
/// - Added support for per-thread data storage.
/// 2.0b: 2009-02-06
/// - Protect communication between TOmniThreadPool and TOTPWorker with a critical
/// section. That should allow multiple threads to Schedule tasks into one
/// thread pool.
/// 2.0a: 2009-02-06
/// - Removed OnWorkerThreadCreated_Asy/OnWorkerThreadDestroyed_Asy
/// notification mechanism which was pretty much useless.
/// 2.0: 2009-01-26
/// - Reimplemented using OmniThreadLibrary :)
/// 1.0: 2008-08-26
/// - First official release.
/// </para></remarks>
unit OtlThreadPool;
{$I OtlOptions.inc}
interface
// TODO 1 -oPrimoz Gabrijelcic : Should be monitorable by the OmniTaskEventDispatch
// TODO 3 -oPrimoz Gabrijelcic : Needs an async event reporting unexpected states (kill threads, for example)
// TODO 5 -oPrimoz Gabrijelcic : Loggers should (maybe) send log info to the event monitor
uses
{$IFDEF MSWINDOWS}
Windows,
{$ELSE}
Diagnostics,
{$ENDIF ~MSWINDOWS}
SysUtils,
OtlCommon,
OtlTask;
const
CDefaultIdleWorkerThreadTimeout_sec = 10;
CDefaultWaitOnTerminate_sec = 30;
type
IOmniThreadPool = interface;
IOmniThreadPoolMonitor = interface
['{09EFADE8-3F14-4184-87CA-131100EC57E4}']
function Detach(const task: IOmniThreadPool): IOmniThreadPool;
{$IFDEF MSWINDOWS}
function Monitor(const task: IOmniThreadPool): IOmniThreadPool;
{$ENDIF MSWINDOWS}
end; { IOmniThreadPoolMonitor }
TThreadPoolOperation = (tpoCreateThread, tpoDestroyThread, tpoKillThread,
tpoWorkItemCompleted);
TOmniThreadPoolMonitorInfo = class
strict private
otpmiTaskID : int64;
otpmiThreadID : integer;
otpmiThreadPoolOperation: TThreadPoolOperation;
otpmiUniqueID : int64;
public
constructor Create(uniqueID: int64; threadPoolOperation: TThreadPoolOperation;
threadID: integer); overload;
constructor Create(uniqueID, taskID: int64); overload;
property TaskID: int64 read otpmiTaskID;
property ThreadPoolOperation: TThreadPoolOperation read
otpmiThreadPoolOperation;
property ThreadID: integer read otpmiThreadID;
property UniqueID: int64 read otpmiUniqueID;
end; { TOmniThreadPoolMonitorInfo }
TOTPThreadDataFactoryFunction = function: IInterface;
TOTPThreadDataFactoryMethod = function: IInterface of object;
/// <summary>Worker thread lifetime reporting handler.</summary>
TOTPWorkerThreadEvent = procedure(Sender: TObject; threadID: TThreadID) of object;
IOmniThreadPool = interface
['{1FA74554-1866-46DD-AC50-F0403E378682}']
function GetIdleWorkerThreadTimeout_sec: integer;
function GetMaxExecuting: integer;
function GetMaxQueued: integer;
function GetMaxQueuedTime_sec: integer;
function GetMinWorkers: integer;
function GetName: string;
function GetUniqueID: int64;
function GetWaitOnTerminate_sec: integer;
procedure SetIdleWorkerThreadTimeout_sec(value: integer);
procedure SetMaxExecuting(value: integer);
procedure SetMaxQueued(value: integer); overload;
procedure SetMaxQueuedTime_sec(value: integer);
procedure SetMinWorkers(value: integer);
procedure SetName(const value: string);
procedure SetWaitOnTerminate_sec(value: integer);
//
function Cancel(taskID: int64): boolean;
procedure CancelAll;
function CountExecuting: integer;
function CountQueued: integer;
function IsIdle: boolean;
function MonitorWith(const monitor: IOmniThreadPoolMonitor): IOmniThreadPool;
function RemoveMonitor: IOmniThreadPool;
function SetMonitor(hWindow: THandle): IOmniThreadPool;
procedure SetThreadDataFactory(const value: TOTPThreadDataFactoryMethod); overload;
procedure SetThreadDataFactory(const value: TOTPThreadDataFactoryFunction); overload;
property IdleWorkerThreadTimeout_sec: integer read GetIdleWorkerThreadTimeout_sec
write SetIdleWorkerThreadTimeout_sec;
property MaxExecuting: integer read GetMaxExecuting write SetMaxExecuting;
property MaxQueued: integer read GetMaxQueued write SetMaxQueued;
property MaxQueuedTime_sec: integer read GetMaxQueuedTime_sec write
SetMaxQueuedTime_sec;
property MinWorkers: integer read GetMinWorkers write SetMinWorkers;
property Name: string read GetName write SetName;
property UniqueID: int64 read GetUniqueID;
property WaitOnTerminate_sec: integer read GetWaitOnTerminate_sec
write SetWaitOnTerminate_sec;
end; { IOmniThreadPool }
IOmniThreadPoolScheduler = interface
['{B7F5FFEF-2704-4CE0-ABF1-B20493E73650}']
procedure Schedule(const task: IOmniTask);
end; { IOmniThreadPoolScheduler }
function CreateThreadPool(const threadPoolName: string): IOmniThreadPool;
function GlobalOmniThreadPool: IOmniThreadPool;
implementation
uses
{$IFDEF MSWINDOWS}
Messages,
Contnrs,
DSiWin32,
GpStuff,
{$ENDIF}
SyncObjs,
Classes,
TypInfo,
{$IFDEF OTL_HasSystemTypes}
System.Types,
{$ENDIF}
{$IFNDEF Unicode} // D2009+ provides own TStringBuilder class
HVStringBuilder,
{$ENDIF}
OtlHooks,
OtlSync,
OtlComm,
OtlContainerObserver,
OtlTaskControl,
OtlEventMonitor;
const
WM_REQUEST_COMPLETED = {$IFDEF MSWINDOWS}WM_USER{$ELSE}1000{$ENDIF};
MSG_RUN = 1;
MSG_THREAD_CREATED = 2;
MSG_THREAD_DESTROYING = 3;
MSG_COMPLETED = 4;
MSG_STOP = 5;
MSG_CANCEL_RESULT = 6;
type
{$IFNDEF Unicode}
TStringBuilder = HVStringBuilder.StringBuilder;
{$ENDIF}
TOTPWorkerThread = class;
TOmniThreadPool = class;
TOTPWorkItem = class
strict private
owiScheduled_ms: int64;
owiScheduledAt : TDateTime;
owiStartedAt : TDateTime;
owiTask : IOmniTask;
owiThread : TOTPWorkerThread;
owiUniqueID : int64;
public
constructor Create(const task: IOmniTask);
function Description: string;
procedure TerminateTask(exitCode: integer; const exitMessage: string);
property ScheduledAt: TDateTime read owiScheduledAt;
property Scheduled_ms: int64 read owiScheduled_ms;
property StartedAt: TDateTime read owiStartedAt write owiStartedAt;
property UniqueID: int64 read owiUniqueID;
property Task: IOmniTask read owiTask;
property Thread: TOTPWorkerThread read owiThread write owiThread;
end; { TOTPWorkItem }
TOTPThreadDataFactory = record
private
tdfExecutable: TOmniExecutable;
public
constructor Create(const a: TOTPThreadDataFactoryFunction); overload;
constructor Create(const a: TOTPThreadDataFactoryMethod); overload;
function Execute: IInterface; inline;
function IsEmpty: boolean; inline;
end; { TOTPThreadDataFactory }
TOTPWorkerThread = class(TThread)
strict private
owtCommChannel : IOmniTwoWayChannel;
owtNewWorkEvent : TOmniTransitionEvent;
owtRemoveFromPool : boolean;
owtStartIdle_ms : int64;
owtStartStopping_ms : int64;
owtStopped : boolean;
owtTerminateEvent : TOmniTransitionEvent;
owtThreadData : IInterface;
owtThreadDataFactory: TOTPThreadDataFactory;
owtWorkItemLock : IOmniCriticalSection;
owtWorkItem_ref : TOTPWorkItem;
strict protected
function Comm: IOmniCommunicationEndpoint;
procedure ExecuteWorkItem(workItem: TOTPWorkItem);
function GetOwnerCommEndpoint: IOmniCommunicationEndpoint;
procedure Log(const msg: string; const params: array of const);
public
constructor Create(const ThreadDataFactory: TOTPThreadDataFactory);
destructor Destroy; override;
procedure Asy_Stop;
function Asy_TerminateWorkItem(var workItem: TOTPWorkItem): boolean;
function Description: string;
procedure Execute; override;
function GetWorkItemInfo(var scheduledAt, startedAt: TDateTime;
var description: string): boolean;
function IsExecuting(taskID: int64): boolean;
procedure Start;
function WorkItemDescription: string;
property NewWorkEvent: TOmniTransitionEvent read owtNewWorkEvent;
property OwnerCommEndpoint: IOmniCommunicationEndpoint read GetOwnerCommEndpoint;
property RemoveFromPool: boolean read owtRemoveFromPool;
property StartIdle_ms: int64 read owtStartIdle_ms write owtStartIdle_ms;
property StartStopping_ms: int64 read owtStartStopping_ms
write owtStartStopping_ms; // always modified from the owner thread
property Stopped: boolean read owtStopped
write owtStopped; // always modified from the owner thread
property TerminateEvent: TOmniTransitionEvent read owtTerminateEvent;
property WorkItem_ref: TOTPWorkItem read owtWorkItem_ref
write owtWorkItem_ref; // address of the work item this thread is working on
end; { TOTPWorkerThread }
TOTPWorker = class(TOmniWorker)
strict private
owDestroying : boolean;
owIdleWorkers : TObjectList;
{$IFDEF MSWINDOWS}
owMonitorObserver : TOmniContainerWindowsMessageObserver;
{$ENDIF MSWINDOWS}
owName : string;
owRunningWorkers : TObjectList;
owStoppingWorkers : TObjectList;
owThreadDataFactory: TOTPThreadDataFactory;
owUniqueID : int64;
owWorkItemQueue : TObjectList;
strict protected
function ActiveWorkItemDescriptions: string;
function CreateWorker: TOTPWorkerThread;
procedure ForwardThreadCreated(threadID: TThreadID);
procedure ForwardThreadDestroying(threadID: TThreadID;
threadPoolOperation: TThreadPoolOperation; worker: TOTPWorkerThread = nil);
procedure InternalStop;
function LocateThread(threadID: DWORD): TOTPWorkerThread;
procedure Log(const msg: string; const params: array of const);
function NumRunningStoppedThreads: integer;
procedure ProcessCompletedWorkItem(workItem: TOTPWorkItem);
procedure RequestCompleted(workItem: TOTPWorkItem; worker: TOTPWorkerThread);
procedure ScheduleNext(workItem: TOTPWorkItem);
procedure StopThread(worker: TOTPWorkerThread);
protected
procedure Cleanup; override;
function Initialize: boolean; override;
public
CountQueued : TOmniAlignedInt32;
CountQueuedLock : TOmniCS;
CountRunning : TOmniAlignedInt32;
IdleWorkerThreadTimeout_sec: TOmniAlignedInt32;
MaxExecuting : TOmniAlignedInt32;
MaxQueued : TOmniAlignedInt32;
MaxQueuedTime_sec : TOmniAlignedInt32;
MinWorkers : TOmniAlignedInt32;
WaitOnTerminate_sec : TOmniAlignedInt32;
constructor Create(const name: string; uniqueID: int64);
published
// invoked from TOmniThreadPool
procedure Cancel(const params: TOmniValue);
procedure CancelAll(var doneSignal: TOmniWaitableValue);
procedure MaintainanceTimer;
// invoked from TOTPWorkerThreads
procedure CheckIdleQueue;
procedure MsgCompleted(var msg: TOmniMessage); {$IFDEF MSWINDOWS}message MSG_COMPLETED;{$ENDIF}
procedure MsgThreadCreated(var msg: TOmniMessage); {$IFDEF MSWINDOWS}message MSG_THREAD_CREATED;{$ENDIF}
procedure MsgThreadDestroying(var msg: TOmniMessage); {$IFDEF MSWINDOWS}message MSG_THREAD_DESTROYING;{$ENDIF}
procedure PruneWorkingQueue;
procedure RemoveMonitor;
procedure Schedule(var workItem: TOTPWorkItem);
procedure SetMonitor(const params: TOmniValue);
procedure SetName(const name: TOmniValue);
procedure SetThreadDataFactory(const threadDataFactory: TOmniValue);
end; { TOTPWorker }
TOTPThreadDataFactoryData = class
strict private
tdfdExecutable: TOTPThreadDataFactory;
public
constructor Create(const executable: TOTPThreadDataFactoryMethod); overload;
constructor Create(const executable: TOTPThreadDataFactoryFunction); overload;
property Executable: TOTPThreadDataFactory read tdfdExecutable;
end; { TOTPThreadDataFactoryData }
TOmniThreadPool = class(TInterfacedObject, IOmniThreadPool, IOmniThreadPoolScheduler)
strict private
otpPoolName : string;
otpThreadDataFactory: TOTPThreadDataFactory;
otpUniqueID : int64;
otpWorker : IOmniWorker;
otpWorkerTask : IOmniTaskControl;
strict protected
procedure Log(const msg: string; const params: array of const);
protected
function GetIdleWorkerThreadTimeout_sec: integer;
function GetMaxExecuting: integer;
function GetMaxQueued: integer;
function GetMaxQueuedTime_sec: integer;
function GetMinWorkers: integer;
function GetName: string;
function GetUniqueID: int64;
function GetWaitOnTerminate_sec: integer;
procedure SetIdleWorkerThreadTimeout_sec(value: integer);
procedure SetMaxExecuting(value: integer);
procedure SetMaxQueued(value: integer);
procedure SetMaxQueuedTime_sec(value: integer);
procedure SetMinWorkers(value: integer);
procedure SetName(const value: string);
procedure SetWaitOnTerminate_sec(value: integer);
function WorkerObj: TOTPWorker;
public
constructor Create(const name: string);
destructor Destroy; override;
function Cancel(taskID: int64): boolean;
procedure CancelAll;
function CountExecuting: integer;
function CountQueued: integer;
function IsIdle: boolean;
function MonitorWith(const monitor: IOmniThreadPoolMonitor): IOmniThreadPool;
function RemoveMonitor: IOmniThreadPool;
procedure Schedule(const task: IOmniTask);
function SetMonitor(hWindow: THandle): IOmniThreadPool;
procedure SetThreadDataFactory(const value: TOTPThreadDataFactoryMethod); overload;
procedure SetThreadDataFactory(const value: TOTPThreadDataFactoryFunction); overload;
property IdleWorkerThreadTimeout_sec: integer
read GetIdleWorkerThreadTimeout_sec write SetIdleWorkerThreadTimeout_sec;
property MaxExecuting: integer read GetMaxExecuting write SetMaxExecuting;
property MaxQueued: integer read GetMaxQueued write SetMaxQueued;
property MaxQueuedTime_sec: integer read GetMaxQueuedTime_sec
write SetMaxQueuedTime_sec;
property MinWorkers: integer read GetMinWorkers write SetMinWorkers;
property Name: string read GetName write SetName;
property UniqueID: int64 read GetUniqueID;
property WaitOnTerminate_sec: integer read GetWaitOnTerminate_sec write
SetWaitOnTerminate_sec;
end; { TOmniThreadPool }
const
CGlobalOmniThreadPoolName = 'GlobalOmniThreadPool';
var
GOmniThreadPool: IOmniThreadPool = nil;
{ exports }
function GlobalOmniThreadPool: IOmniThreadPool;
begin
if not assigned(GOmniThreadPool) then
GOmniThreadPool := CreateThreadPool(CGlobalOmniThreadPoolName);
Result := GOmniThreadPool;
end; { GlobalOmniThreadPool }
function CreateThreadPool(const threadPoolName: string): IOmniThreadPool;
begin
Result := TOmniThreadPool.Create(threadPoolName);
end; { CreateThreadPool }
{ TOmniThreadPoolMonitorInfo }
constructor TOmniThreadPoolMonitorInfo.Create(uniqueID: int64;
threadPoolOperation: TThreadPoolOperation; threadID: integer);
begin
otpmiUniqueID := uniqueID;
otpmiThreadPoolOperation := threadPoolOperation;
otpmiThreadID := threadID;
end; { TOmniThreadPoolMonitorInfo.Create }
constructor TOmniThreadPoolMonitorInfo.Create(uniqueID, taskID: int64);
begin
otpmiUniqueID := uniqueID;
otpmiThreadPoolOperation := tpoWorkItemCompleted;
otpmiTaskID := taskID;
end; { TOmniThreadPoolMonitorInfo.Create }
{ TOTPThreadDataFactory }
constructor TOTPThreadDataFactory.Create(const a: TOTPThreadDataFactoryFunction);
begin
tdfExecutable.Proc := TProcedure(a);
end; { TOTPThreadDataFactory.Create }
constructor TOTPThreadDataFactory.Create(const a: TOTPThreadDataFactoryMethod);
begin
tdfExecutable.Method := TMethod(a);
end; { TOTPThreadDataFactory.Create }
function TOTPThreadDataFactory.Execute: IInterface;
begin
case tdfExecutable.Kind of
oekProcedure:
Result := TOTPThreadDataFactoryFunction(tdfExecutable.Proc)();
oekMethod:
Result := TOTPThreadDataFactoryMethod(tdfExecutable.Method)();
else raise Exception.Create('TOTPThreadDataFactory.Execute: Not supported!');
end;
end; { TOTPThreadDataFactory.Execute }
function TOTPThreadDataFactory.IsEmpty: boolean;
begin
Result := tdfExecutable.IsNull;
end; { TOTPThreadDataFactory.IsEmpty }
{ TOTPWorkItem }
constructor TOTPWorkItem.Create(const task: IOmniTask);
begin
inherited Create;
owiTask := task;
owiScheduledAt := Now;
owiScheduled_ms := {$IFDEF MSWINDOWS} DSiTimeGetTime64 {$ELSE} TStopWatch.GetTimeStamp {$ENDIF};
owiUniqueID := owiTask.UniqueID;
end; { TOTPWorkItem.Create }
function TOTPWorkItem.Description: string;
begin
if assigned(Task) then
Result := Format('%s:%d', [Task.Name, UniqueID])
else
Result := Format(':%d', [UniqueID]);
end; { TOTPWorkItem.Description }
procedure TOTPWorkItem.TerminateTask(exitCode: integer; const exitMessage: string);
begin
if assigned(owiTask) then begin
owiTask.Enforced(false);
owiTask.SetExitStatus(exitCode, exitMessage);
owiTask.Terminate;
owiTask := nil;
end;
end; { TOTPWorkItem.TerminateTask }
{ TOTPWorkerThread }
constructor TOTPWorkerThread.Create(const ThreadDataFactory: TOTPThreadDataFactory);
begin
inherited Create(true);
{$IFDEF LogThreadPool}Log('Creating thread %s', [Description]);{$ENDIF LogThreadPool}
owtThreadDataFactory := ThreadDataFactory;
{$IFDEF MSWINDOWS}
owtNewWorkEvent := CreateEvent(nil, false, false, nil);
owtTerminateEvent := CreateEvent(nil, false, false, nil);
{$ELSE}
owtNewWorkEvent := CreateOmniEvent(false, false);
owtTerminateEvent := CreateOmniEvent(false, false);
{$ENDIF ~MSWINDOWS}
owtWorkItemLock := CreateOmniCriticalSection;
owtCommChannel := CreateTwoWayChannel(100, owtTerminateEvent);
end; { TOTPWorkerThread.Create }
destructor TOTPWorkerThread.Destroy;
begin
{$IFDEF LogThreadPool}Log('Destroying thread %s', [Description]);{$ENDIF LogThreadPool}
owtWorkItemLock := nil;
{$IFDEF MSWINDOWS}
DSiCloseHandleAndNull(owtTerminateEvent);
DSiCloseHandleAndNull(owtNewWorkEvent);
{$ELSE}
owtTerminateEvent := nil;
owtNewWorkEvent := nil;
{$ENDIF ~MSWINDOWS}
inherited Destroy;
end; { TOTPWorkerThread.Destroy }
/// <summary>Gently stop the worker thread.
procedure TOTPWorkerThread.Asy_Stop;
var
task: IOmniTask;
begin
{$IFDEF LogThreadPool}Log('Stop thread %s', [Description]);{$ENDIF LogThreadPool}
if assigned(owtWorkItemLock) then begin // Stop may be called during Cancel[All] and owtWorkItemLock may already be destroyed
owtWorkItemLock.Acquire;
try
if assigned(WorkItem_ref) then begin
task := WorkItem_ref.task;
if assigned(task) then
task.Terminate;
end;
finally owtWorkItemLock.Release end;
end;
end; { TOTPWorkerThread.Asy_Stop }
/// <summary>Take the work item ownership from the thread. Called asynchronously from the thread pool.</summary>
/// <returns>True if thread should be killed.</returns>
/// <since>2008-07-26</since>
function TOTPWorkerThread.Asy_TerminateWorkItem(var workItem: TOTPWorkItem): boolean;
begin
{$IFDEF LogThreadPool}Log('Asy_TerminateWorkItem thread %s', [Description]);{$ENDIF LogThreadPool}
Result := false;
owtWorkItemLock.Acquire;
try
if assigned(WorkItem_ref) then begin
{$IFDEF LogThreadPool}Log('Thread %s has work item', [Description]);{$ENDIF LogThreadPool}
workItem := WorkItem_ref;
WorkItem_ref := nil;
if assigned(workItem) and assigned(workItem.task) and
(not workItem.task.Stopped) then
begin
workItem.TerminateTask(EXIT_THREADPOOL_CANCELLED, 'Cancelled');
Result := true;
end
else if assigned(workItem) then
Result := false;
end;
finally owtWorkItemLock.Release; end;
end; { TOTPWorkerThread.Asy_TerminateWorkItem }
function TOTPWorkerThread.Comm: IOmniCommunicationEndpoint;
begin
Result := owtCommChannel.Endpoint1;
end; { TOTPWorkerThread.Comm }
function TOTPWorkerThread.Description: string;
begin
if not assigned(Self) then
Result := '<none>'
else
Result := Format('%p:%d', [pointer(Self), ThreadID]);
end; { TOTPWorkerThread.Description }
procedure TOTPWorkerThread.Execute;
var
msg: TOmniMessage;
begin
{$IFDEF LogThreadPool}Log('>>>Execute thread %s', [Description]);{$ENDIF LogThreadPool}
SendThreadNotifications(tntCreate, 'OtlThreadPool worker');
try
Comm.Send(MSG_THREAD_CREATED, threadID);
try
if owtThreadDataFactory.IsEmpty then
owtThreadData := nil
else
owtThreadData := owtThreadDataFactory.Execute;
while true do begin
if Comm.ReceiveWait(msg, INFINITE) then begin
case msg.MsgID of
MSG_RUN:
ExecuteWorkItem(TOTPWorkItem(msg.MsgData.AsObject));
MSG_STOP:
break; // while
else
raise Exception.CreateFmt(
'TOTPWorkerThread.Execute: Unexpected message %d', [msg.MsgID]);
end; // case
end; // if Comm.ReceiveWait
end; // while Comm.ReceiveWait()
finally Comm.Send(MSG_THREAD_DESTROYING, threadID); end;
finally SendThreadNotifications(tntDestroy, 'OtlThreadPool worker'); end;
{$IFDEF LogThreadPool}Log('<<<Execute thread %s', [Description]);{$ENDIF LogThreadPool}
end; { TOTPWorkerThread.Execute }
procedure TOTPWorkerThread.ExecuteWorkItem(workItem: TOTPWorkItem);
{$IFDEF LogThreadPool}
var
creationTime : TDateTime;
startKernelTime: int64;
startUserTime : int64;
stopKernelTime : int64;
stopUserTime : int64;
{$ENDIF LogThreadPool}
var
task: IOmniTask;
begin
WorkItem_ref := workItem;
task := WorkItem_ref.task;
try
{$IFDEF LogThreadPool}Log('Thread %s starting execution of %s', [Description, WorkItem_ref.Description]);
DSiGetThreadTimes(creationTime, startUserTime, startKernelTime); {$ENDIF LogThreadPool}
if assigned(task) then
with (task as IOmniTaskExecutor) do begin
SetThreadData(owtThreadData);
Execute;
end;
{$IFDEF LogThreadPool}DSiGetThreadTimes(creationTime, stopUserTime, stopKernelTime);
Log(
'Thread %s completed execution of %s; user time = %d ms, kernel time = %d ms',
[Description, WorkItem_ref.Description, Round
((stopUserTime - startUserTime) / 10000), Round
((stopKernelTime - startKernelTime) / 10000)]); {$ENDIF LogThreadPool}
finally task := nil; end;
if assigned(owtWorkItemLock) then owtWorkItemLock.Acquire;
try
workItem := WorkItem_ref;
WorkItem_ref := nil;
if assigned(workItem) then begin // not already canceled
{$IFDEF LogThreadPool}Log(
'Thread %s sending notification of completed work item %s',
[Description, workItem.Description]); {$ENDIF LogThreadPool}
Comm.Send(MSG_COMPLETED, workItem);
end;
finally if assigned(owtWorkItemLock) then owtWorkItemLock.Release; end;
SetThreadName('Idle thread worker');
end; { TOTPWorkerThread.ExecuteWorkItem }
function TOTPWorkerThread.GetOwnerCommEndpoint: IOmniCommunicationEndpoint;
begin
Result := owtCommChannel.Endpoint2;
end; { TOTPWorkerThread.GetOwnerCommEndpoint }
function TOTPWorkerThread.GetWorkItemInfo(var scheduledAt, startedAt: TDateTime;
var description: string): boolean;
begin
owtWorkItemLock.Acquire;
try
if not assigned(WorkItem_ref) then
Result := false
else begin
scheduledAt := WorkItem_ref.scheduledAt;
startedAt := WorkItem_ref.startedAt;
description := WorkItem_ref.description;
UniqueString(description);
Result := true;
end;
finally owtWorkItemLock.Release; end;
end; { TOTPWorkerThread.GetWorkItemInfo }
function TOTPWorkerThread.IsExecuting(taskID: int64): boolean;
begin
owtWorkItemLock.Acquire;
try
Result := assigned(WorkItem_ref) and (WorkItem_ref.UniqueID = taskID);
finally owtWorkItemLock.Release; end;
end; { TOTPWorkerThread.IsExecuting }
procedure TOTPWorkerThread.Log(const msg: string; const params: array of const);
begin
{$IFDEF LogThreadPool}
OutputDebugString(PChar(Format(msg, params)));
{$ENDIF LogThreadPool}
end; { TOTPWorkerThread.Log }
procedure TOTPWorkerThread.Start;
begin
{$IFDEF OTL_DeprecatedResume}
inherited Start;
{$ELSE}
inherited Resume;
{$ENDIF OTL_DeprecatedResume}
end; { TOTPWorkerThread.Start }
function TOTPWorkerThread.WorkItemDescription: string;
begin
owtWorkItemLock.Acquire;
try
if assigned(WorkItem_ref) then
Result := WorkItem_ref.Description
else
Result := '';
finally owtWorkItemLock.Release; end;
end; { TOTPWorkerThread.WorkItemDescription }
{ TOTPWorker }
constructor TOTPWorker.Create(const name: string; uniqueID: int64);
begin
inherited Create;
owName := name;
owUniqueID := uniqueID;
end; { TOTPWorker.Create }
function TOTPWorker.ActiveWorkItemDescriptions: string;
var
description : string;
iWorker : integer;
sbDescriptions: TStringBuilder;
ScheduledAt : TDateTime;
StartedAt : TDateTime;
worker : TOTPWorkerThread;
begin
sbDescriptions := TStringBuilder.Create;
try
for iWorker := 0 to owRunningWorkers.Count - 1 do begin
worker := TOTPWorkerThread(owRunningWorkers[iWorker]);
if worker.GetWorkItemInfo(ScheduledAt, StartedAt, description)
then
sbDescriptions.Append('[').Append(iWorker + 1).Append('] ').Append
(FormatDateTime('hh:nn:ss', ScheduledAt)).Append(' / ').Append
(FormatDateTime('hh:nn:ss', StartedAt)).Append(' ').Append
(description);
end;
Result := sbDescriptions.ToString;
finally FreeAndNil(sbDescriptions); end;
end; { TGpThreadPool.ActiveWorkItemDescriptions }
/// <returns>True: Normal exit, False: Thread was killed.</returns>
procedure TOTPWorker.Cancel(const params: TOmniValue);
var
endWait_ms : int64;
iWorker : integer;
taskID : int64;
waitParam : TOmniValue;
wasTerminated: boolean;
worker : TOTPWorkerThread;
workItem : TOTPWorkItem;
begin
taskID := params[0];
wasTerminated := true;
for iWorker := 0 to owRunningWorkers.Count - 1 do begin
worker := TOTPWorkerThread(owRunningWorkers[iWorker]);
if worker.IsExecuting(taskID) then begin
{$IFDEF LogThreadPool}Log('Cancel request %d on thread %p:%d', [taskID, pointer(worker), worker.threadID]); {$ENDIF LogThreadPool}
owRunningWorkers.Delete(iWorker);
worker.Asy_Stop;
endWait_ms := {$IFDEF MSWINDOWS} DSiTimeGetTime64 {$ELSE} TStopWatch.GetTimeStamp {$ENDIF} + int64(WaitOnTerminate_sec.Value) * 1000;
while ({$IFDEF MSWINDOWS} DSiTimeGetTime64 {$ELSE} TStopWatch.GetTimeStamp {$ENDIF} < endWait_ms) and (not worker.Stopped) do begin
ProcessMessages;
Sleep(10);
end;
{$IFDEF MSWINDOWS}
SuspendThread(worker.Handle);
{$ELSE}
worker.Suspended := true;
{$ENDIF ~MSWINDOWS}
if worker.Asy_TerminateWorkItem(workItem) then begin
ProcessCompletedWorkItem(workItem);
{$IFDEF LogThreadPool}Log(
'Terminating unstoppable thread %s, num idle = %d, num running = %d[%d]',
[worker.Description, owIdleWorkers.Count, owRunningWorkers.Count,
MaxExecuting.Value]); {$ENDIF LogThreadPool}
{$IFDEF MSWINDOWS}
TerminateThread(worker.Handle, cardinal(-1));
{$ELSE}
worker.Terminate;
{$ENDIF ~MSWINDOWS}
ForwardThreadDestroying(worker.threadID, tpoKillThread, worker);
FreeAndNil(worker);
wasTerminated := false;
end
else begin
{$IFDEF MSWINDOWS}
ResumeThread(worker.Handle);
{$ELSE}
worker.Suspended := false;
{$ENDIF ~MSWINDOWS}
owIdleWorkers.Add(worker);
{$IFDEF LogThreadPool}Log(
'Thread %s moved to the idle list, num idle = %d, num running = %d[%d]',
[worker.Description, owIdleWorkers.Count, owRunningWorkers.Count,
MaxExecuting.Value]); {$ENDIF LogThreadPool}
end;
break; // for
end;
end; // for iWorker
waitParam := params[1];
(waitParam.AsObject as TOmniWaitableValue).Signal(wasTerminated);
end; { TOTPWorker.Cancel }
procedure TOTPWorker.CancelAll(var doneSignal: TOmniWaitableValue);
begin
InternalStop;
doneSignal.Signal;
end; { TOTPWorker.CancelAll }
procedure TOTPWorker.Cleanup;
begin
owDestroying := true;
InternalStop;
FreeAndNil(owStoppingWorkers);
FreeAndNil(owRunningWorkers);
FreeAndNil(owIdleWorkers);
FreeAndNil(owWorkItemQueue);
end; { TOTPWorker.Cleanup }
procedure TOTPWorker.ForwardThreadCreated(threadID: TThreadID);
begin
{$IFDEF MSWINDOWS}
if assigned(owMonitorObserver) then
owMonitorObserver.Send(COmniPoolMsg, 0, cardinal
(TOmniThreadPoolMonitorInfo.Create(owUniqueID, tpoCreateThread, threadID))
);
{$ENDIF MSWINDOWS}
end; { TOTPWorker.ForwardThreadCreated }
procedure TOTPWorker.ForwardThreadDestroying(threadID: TThreadID;
threadPoolOperation: TThreadPoolOperation; worker: TOTPWorkerThread);
begin
if not assigned(worker) then
worker := LocateThread(threadID);
if assigned(worker) then begin
task.UnregisterComm(worker.OwnerCommEndpoint);
worker.Stopped := true;
end;
{$IFDEF MSWINDOWS}
if assigned(owMonitorObserver) then
owMonitorObserver.Send(COmniPoolMsg, 0, cardinal
(TOmniThreadPoolMonitorInfo.Create(owUniqueID, threadPoolOperation,
threadID)));
{$ENDIF MSWINDOWS}
end; { TOTPWorker.ForwardThreadDestroying }
function TOTPWorker.Initialize: boolean;
begin
owIdleWorkers := TObjectList.Create(false);
owRunningWorkers := TObjectList.Create(false);
CountRunning.Value := 0;
owStoppingWorkers := TObjectList.Create(false);
owWorkItemQueue := TObjectList.Create(false);
CountQueued.Value := 0;
IdleWorkerThreadTimeout_sec.Value := CDefaultIdleWorkerThreadTimeout_sec;
WaitOnTerminate_sec.Value := CDefaultWaitOnTerminate_sec;
MaxExecuting.Value := Environment.Process.Affinity.Count;
Task.SetTimer(1, 1000, @TOTPWorker.MaintainanceTimer);
Result := true;
end; { TOTPWorker.Initialize }
procedure TOTPWorker.InternalStop;
var
endWait_ms: int64;
iWorker: integer;
iWorkItem: integer;
queuedItems: TObjectList { of TOTPWorkItem } ;
worker: TOTPWorkerThread;
workItem: TOTPWorkItem;
begin
{$IFDEF LogThreadPool}Log('Terminating queued tasks', []);{$ENDIF LogThreadPool}
queuedItems := TObjectList.Create(false);
try
for iWorkItem := 0 to owWorkItemQueue.Count - 1 do
queuedItems.Add(owWorkItemQueue[iWorkItem]);
owWorkItemQueue.Clear;
CountQueued.Value := 0;
for iWorkItem := 0 to queuedItems.Count - 1 do begin
workItem := TOTPWorkItem(queuedItems[iWorkItem]);
workItem.TerminateTask(EXIT_THREADPOOL_CANCELLED, 'Cancelled');
RequestCompleted(workItem, nil);
end; // for iWorkItem
finally FreeAndNil(queuedItems); end;
{$IFDEF LogThreadPool}Log('Stopping all threads', []); {$ENDIF LogThreadPool}
for iWorker := 0 to owIdleWorkers.Count - 1 do
StopThread(TOTPWorkerThread(owIdleWorkers[iWorker]));
owIdleWorkers.Clear;
for iWorker := 0 to owRunningWorkers.Count - 1 do
StopThread(TOTPWorkerThread(owRunningWorkers[iWorker]));
owRunningWorkers.Clear;
CountRunning.Value := 0;
endWait_ms := {$IFDEF MSWINDOWS} DSiTimeGetTime64 {$ELSE} TStopWatch.GetTimeStamp {$ENDIF} + int64(WaitOnTerminate_sec.Value) * 1000;
while (endWait_ms > {$IFDEF MSWINDOWS} DSiTimeGetTime64 {$ELSE} TStopWatch.GetTimeStamp {$ENDIF}) and (NumRunningStoppedThreads > 0) do
begin
ProcessMessages;
// TODO 1 -oPrimoz Gabrijelcic : ! what happens here during CancelAll? can the task die? !
Sleep(10);
end;
for iWorker := 0 to owStoppingWorkers.Count - 1 do begin
worker := TOTPWorkerThread(owStoppingWorkers[iWorker]);
worker.Asy_TerminateWorkItem(workItem);
FreeAndNil(worker);
end;
owStoppingWorkers.Clear;
end; { TOTPWorker.InternalStop }
function TOTPWorker.LocateThread(threadID: DWORD): TOTPWorkerThread;
var
oThread: pointer;
begin
for oThread in owRunningWorkers do begin
Result := TOTPWorkerThread(oThread);
if Result.threadID = threadID then
Exit;
end;
for oThread in owIdleWorkers do begin
Result := TOTPWorkerThread(oThread);
if Result.threadID = threadID then
Exit;
end;
for oThread in owStoppingWorkers do begin
Result := TOTPWorkerThread(oThread);
if Result.threadID = threadID then
Exit;
end;
Result := nil;
end; { TOTPWorker.LocateThread }
procedure TOTPWorker.Log(const msg: string; const params: array of const );
begin
{$IFDEF LogThreadPool}
OutputDebugString(PChar(Format(msg, params)));
{$ENDIF LogThreadPool}
end; { TOTPWorker.Log }
procedure TOTPWorker.MaintainanceTimer;
var
iWorker: integer;
worker : TOTPWorkerThread;
begin
PruneWorkingQueue;
if IdleWorkerThreadTimeout_sec > 0 then begin