forked from gabr42/OmniThreadLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OtlThreadPool.pas
2148 lines (1975 loc) · 80.7 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) 2020, 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://en.delphipraxis.net/forum/32-omnithreadlibrary/
/// 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 : 2021-02-23
/// Version : 2.20a
/// </para><para>
/// History:
/// 2.20a: 2021-02-23
/// - Fixed TOmniThreadPool.Destroy when TOmniThreadPool.Create raised an exception.
/// 2.20: 2020-12-21
/// - Added optional timeout parameter to IOmniThreadPool.Cancel.
/// 2.19b: 2019-02-10
/// - Thread pool creation code waits for thread pool management thread to be
/// started and initialized. Without that, CountQueued and CountExecuting may
/// not be initialized yet when thread pool creation code exits.
/// 2.19a: 2018-03-12
/// - ThreadData is destroyed in the worker thread and not in the thread pool
/// management thread.
/// 2.19: 2017-11-28
/// - Worker thread name is set to 'Idle thread worker' only when worker has no work.
/// 2.18a: 2017-05-29
/// - Did not compile when NUMA support was enabled.
/// 2.18: 2017-05-27
/// - Breaking change: Cancel(taskID) will signal task's cancellation token before
/// calling task's Terminate method.
/// CancelAll will signal cancellation token for all running
/// tasks before calling their Terminate method.
/// Old behaviour (no CancellationToken.Signal before Terminate) can be achieved
/// by calling overloaded version of the functions accepting the
/// `signalCancellationToken` parameter or by setting
/// IOmniThreadPool.Options to [tpoPreventCancellationTokenOnCancel].
/// 2.17a: 2017-04-04
/// - TOTPWorker.Cancel must use `while`, not `for`, as owRunningWorkers.Count can
/// change during the execution.
/// 2.17: 2017-02-03
/// - If ThreadDataFactory.Execute throws an exception, that exception is caught,
/// ignored and ThreadData is set to nil. [issue #88]
/// 2.16a: 2017-01-17
/// - Fix: IdleWorkerThreadTimeout_sec and WaitOnTerminate_sec were initialized
/// too late.
/// 2.16: 2017-01-16
/// - Reverted [2.14]: Any change to Affinity, ProcessorGroups, or NUMANodes
/// properties will reset the MaxExecuting.
/// - New behaviour is compatible with the pre-2.14 code: Initially, MaxExecuting is
/// set to Environment.Process.Affinity.Count. This value can only be changed by
/// the external code, not inside the OtlThreadPool unit.
/// - Added readonly property IOmniThreadPool.NumCores which returns number of cores
/// this pool uses for running tasks. This value can be changed after Affinity,
/// ProcessorGroups, or NUMANodes properties are modified.
/// 2.15a: 2016-09-05
/// - TOmniThreadPool.Create no longer waits on thread to be initialized. This
/// allows a thread pool to be created inside DLL initialization code.
/// [https://msdn.microsoft.com/en-us/library/windows/desktop/ms682453(v=vs.85).aspx]
/// 2.15: 2016-08-31
/// - In the past, unhandled exceptions in the code handling the task execution
/// were lost. Now, they are passed up to the IOmniThreadPool. If its property
/// Asy_OnUnhandledWorkerException is set, exception will be passed to the event
/// handler and application should react to it. The only safe way at that point
/// is to log the error (and stack trace for the current thread) and terminate
/// the application.
/// - TOmniThreadPool creation/destruction notifications are sent via OtlHook.
/// 2.14: 2016-07-14
/// - Any change to Affinity, ProcessorGroups, or NUMANodes properties will reset
/// the MaxExecuting count.
/// - Changes to Affinity, ProcessorGroups, and NUMANodes properties are synchronous.
/// 2.13: 2016-07-13
/// - Implemented NUMA and Processor group support.
/// 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}
Contnrs,
Classes,
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;
TOTPUnhandledWorkerException = procedure(thread: TThread; E: Exception) of object;
/// <summary>Worker thread lifetime reporting handler.</summary>
TOTPWorkerThreadEvent = procedure(Sender: TObject; threadID: TThreadID) of object;
TOmniThreadPoolOption = (tpoPreventCancellationTokenOnCancel);
TOmniThreadPoolOptions = set of TOmniThreadPoolOption;
IOmniThreadPool = interface
['{1FA74554-1866-46DD-AC50-F0403E378682}']
function GetAsy_OnUnhandledWorkerException: TOTPUnhandledWorkerException;
function GetIdleWorkerThreadTimeout_sec: integer;
function GetMaxExecuting: integer;
function GetMaxQueued: integer;
function GetMaxQueuedTime_sec: integer;
function GetMinWorkers: integer;
function GetName: string;
function GetNumCores: integer;
function GetUniqueID: int64;
function GetWaitOnTerminate_sec: integer;
procedure SetAsy_OnUnhandledWorkerException(const Value: TOTPUnhandledWorkerException);
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; timeout_ms: int64 = -1 {use WaitOnTerminate_sec}): boolean; overload;
function Cancel(taskID: int64; signalCancellationToken: boolean; timeout_ms: int64 = -1 {use WaitOnTerminate_sec}): boolean; overload;
procedure CancelAll; overload;
procedure CancelAll(signalCancellationToken: boolean); overload;
function CountExecuting: integer;
function CountQueued: integer;
function GetAffinity: IOmniIntegerSet;
function GetOptions: TOmniThreadPoolOptions;
function IsIdle: boolean;
function MonitorWith(const monitor: IOmniThreadPoolMonitor): IOmniThreadPool;
function RemoveMonitor: IOmniThreadPool;
function SetMonitor(hWindow: THandle): IOmniThreadPool;
procedure SetOptions(const value: TOmniThreadPoolOptions);
procedure SetThreadDataFactory(const value: TOTPThreadDataFactoryMethod); overload;
procedure SetThreadDataFactory(const value: TOTPThreadDataFactoryFunction); overload;
{$IFDEF OTL_NUMASupport}
function GetNUMANodes: IOmniIntegerSet;
function GetProcessorGroups: IOmniIntegerSet;
procedure SetNUMANodes(const value: IOmniIntegerSet);
procedure SetProcessorGroups(const value: IOmniIntegerSet);
{$ENDIF OTL_NUMASupport}
property IdleWorkerThreadTimeout_sec: integer read GetIdleWorkerThreadTimeout_sec
write SetIdleWorkerThreadTimeout_sec;
property Asy_OnUnhandledWorkerException: TOTPUnhandledWorkerException read
GetAsy_OnUnhandledWorkerException write SetAsy_OnUnhandledWorkerException;
property Affinity: IOmniIntegerSet read GetAffinity;
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 NumCores: integer read GetNumCores;
property Options: TOmniThreadPoolOptions read GetOptions write SetOptions;
property UniqueID: int64 read GetUniqueID;
property WaitOnTerminate_sec: integer read GetWaitOnTerminate_sec
write SetWaitOnTerminate_sec;
{$IFDEF OTL_NUMASupport}
property ProcessorGroups: IOmniIntegerSet read GetProcessorGroups write
SetProcessorGroups;
property NUMANodes: IOmniIntegerSet read GetNUMANodes write SetNUMANodes;
{$ENDIF OTL_NUMASupport}
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,
DSiWin32,
GpStuff,
{$ENDIF}
Math,
SyncObjs,
TypInfo,
{$IFDEF OTL_HasSystemTypes}
System.Types,
{$ENDIF}
{$IFNDEF Unicode} // D2009+ provides own TStringBuilder class
HVStringBuilder,
{$ENDIF}
OtlHooks,
OtlSync,
OtlCommon.Utils,
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
owiGroupAffinity: TOmniGroupAffinity;
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 GroupAffinity: TOmniGroupAffinity read owiGroupAffinity write owiGroupAffinity;
property Scheduled_ms: int64 read owiScheduled_ms;
property ScheduledAt: TDateTime read owiScheduledAt;
property StartedAt: TDateTime read owiStartedAt write owiStartedAt;
property Task: IOmniTask read owiTask;
property Thread: TOTPWorkerThread read owiThread write owiThread;
property UniqueID: int64 read owiUniqueID;
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
owtAsy_OnUnhandledException: TOTPUnhandledWorkerException;
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 GetMsg(var msg: TOmniMessage): boolean;
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(signalCancellationToken: boolean = false);
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 Asy_OnUnhandledException: TOTPUnhandledWorkerException read
owtAsy_OnUnhandledException write owtAsy_OnUnhandledException;
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 }
TOTPGroupAffinity = class
private
FAffinity: int64;
FError : integer;
FGroup : integer;
FProcCount: integer;
strict protected
procedure SetAffinity(const value: int64);
public
constructor Create(group: integer; affinity: int64);
property Affinity: int64 read FAffinity write SetAffinity;
property Group: integer read FGroup;
property ProcessorCount: integer read FProcCount;
property Error: integer read FError write FError;
end; { TOTPGroupAffinity }
TOTPWorkerScheduler = class
strict private
owsClusters : TObjectList {of TOTPGroupAffinity};
owsNextCluster: integer;
owsRoundRobin : array of integer;
strict protected
procedure ApplyAffinityMask(const affinity: IOmniIntegerSet);
procedure CreateInitialClusters(const processorGroups, numaNodes: IOmniIntegerSet);
procedure CreateRoundRobin;
function FindHighestError: integer;
function GetCluster(idx: integer): TOTPGroupAffinity; inline;
function IsSame(value1, value2: TOTPGroupAffinity): boolean; inline;
procedure RemoveDuplicateClusters;
public
constructor Create;
destructor Destroy; override;
function Count: integer; inline;
function Next: TOmniGroupAffinity;
procedure Update(affinity, processorGroups, numaNodes: IOmniIntegerSet);
property Cluster[idx: integer]: TOTPGroupAffinity read GetCluster;
end; { TOTPWorkerScheduler }
IOTPWorker = interface ['{27C4FD6F-86A2-45FC-8EE4-20A80ECC84FA}']
function GetAsy_OnUnhandledWorkerException: TOTPUnhandledWorkerException;
procedure SetAsy_OnUnhandledWorkerException(const Value: TOTPUnhandledWorkerException);
//
property Asy_OnUnhandledWorkerException: TOTPUnhandledWorkerException read
GetAsy_OnUnhandledWorkerException write SetAsy_OnUnhandledWorkerException;
end; { IOTPWorker }
TOTPWorker = class(TOmniWorker, IOTPWorker)
strict private
owAffinity : IOmniIntegerSet;
owAsy_OnUnhandledWorkerException: TOTPUnhandledWorkerException;
owDestroying : boolean;
owIdleWorkers : TObjectList;
{$IFDEF MSWINDOWS}
owMonitorObserver : TOmniContainerWindowsMessageObserver;
{$ENDIF MSWINDOWS}
owName : string;
owNUMANodes : IOmniIntegerSet;
owProcessorGroups : IOmniIntegerSet;
owRunningWorkers : TObjectList;
owScheduler : TOTPWorkerScheduler;
owStoppingWorkers : TObjectList;
owThreadDataFactory : TOTPThreadDataFactory;
owUniqueID : int64;
owWorkItemQueue : TObjectList;
strict protected
function ActiveWorkItemDescriptions: string;
procedure Asy_ForwardUnhandledWorkerException(thread: TThread; E: Exception);
function CreateWorker: TOTPWorkerThread;
procedure ForwardThreadCreated(threadID: TThreadID);
procedure ForwardThreadDestroying(threadID: TThreadID;
threadPoolOperation: TThreadPoolOperation; worker: TOTPWorkerThread = nil);
procedure InternalStop(signalCancellationToken: boolean = false);
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; signalCancellationToken: boolean = false);
procedure UpdateScheduler;
protected
procedure Cleanup; override;
function GetAsy_OnUnhandledWorkerException: TOTPUnhandledWorkerException;
function Initialize: boolean; override;
procedure SetAsy_OnUnhandledWorkerException(const value: TOTPUnhandledWorkerException);
public
CountQueued : TOmniAlignedInt32;
CountQueuedLock : TOmniCS;
CountRunning : TOmniAlignedInt32;
IdleWorkerThreadTimeout_sec: TOmniAlignedInt32;
MaxExecuting : TOmniAlignedInt32;
MaxQueued : TOmniAlignedInt32;
MaxQueuedTime_sec : TOmniAlignedInt32;
MinWorkers : TOmniAlignedInt32;
NumCores : TOmniAlignedInt32;
WaitOnTerminate_sec : TOmniAlignedInt32;
constructor Create(const name: string; uniqueID: int64);
property Asy_OnUnhandledWorkerException: TOTPUnhandledWorkerException read
GetAsy_OnUnhandledWorkerException write SetAsy_OnUnhandledWorkerException;
// 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 SetAffinity(const value: TOmniValue);
procedure SetMonitor(const params: TOmniValue);
procedure SetNUMANodes(const value: TOmniValue);
procedure SetProcessorGroups(const value: TOmniValue);
procedure SetName(const name: TOmniValue);
procedure SetThreadDataFactory(const threadDataFactory: TOmniValue);
// invoked from TOmniThreadPool
procedure Cancel(const params: TOmniValue);
procedure CancelAll(const params: TOmniValue);
procedure MaintainanceTimer;
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
FOptions: TOmniThreadPoolOptions;
otpAffinity : IOmniIntegerSet;
otpAsy_OnUnhandledWorkerException: TOTPUnhandledWorkerException;
otpPoolName : string;
otpThreadDataFactory : TOTPThreadDataFactory;
otpUniqueID : int64;
otpWorker : IOmniWorker;
otpWorkerTask : IOmniTaskControl;
{$IFDEF OTL_NUMASupport}
otpNUMANodes : IOmniIntegerSet;
otpProcessorGroups : IOmniIntegerSet;
{$ENDIF OTL_NUMASupport}
protected
procedure Asy_ForwardUnhandledWorkerException(thread: TThread; E: Exception);
function GetAffinity: IOmniIntegerSet;
function GetAsy_OnUnhandledWorkerException: TOTPUnhandledWorkerException;
function GetIdleWorkerThreadTimeout_sec: integer;
function GetMaxExecuting: integer;
function GetMaxQueued: integer;
function GetMaxQueuedTime_sec: integer;
function GetMinWorkers: integer;
function GetName: string;
function GetNumCores: integer;
function GetOptions: TOmniThreadPoolOptions;
function GetUniqueID: int64;
function GetWaitOnTerminate_sec: integer;
procedure Log(const msg: string; const params: array of const);
procedure NotifyAffinityChanged(const value: IOmniIntegerSet);
procedure SetAsy_OnUnhandledWorkerException(const value: TOTPUnhandledWorkerException);
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 SetOptions(const value: TOmniThreadPoolOptions);
procedure SetWaitOnTerminate_sec(value: integer);
function WorkerObj: TOTPWorker;
{$IFDEF OTL_NUMASupport}
function GetNUMANodes: IOmniIntegerSet;
function GetProcessorGroups: IOmniIntegerSet;
procedure NotifyNUMANodesChanged(const value: IOmniIntegerSet);
procedure NotifyProcessorGroupsChanged(const value: IOmniIntegerSet);
procedure SetNUMANodes(const value: IOmniIntegerSet);
procedure SetProcessorGroups(const value: IOmniIntegerSet);
{$ENDIF OTL_NUMASupport}
public
constructor Create(const name: string);
destructor Destroy; override;
function Cancel(taskID: int64; timeout_ms: int64 = -1 {use WaitOnTerminate_sec}): boolean; overload;
function Cancel(taskID: int64; signalCancellationToken: boolean; timeout_ms: int64 = -1 {use WaitOnTerminate_sec}): boolean; overload;
procedure CancelAll; overload;
procedure CancelAll(signalCancellationToken: boolean); overload;
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 Asy_OnUnhandledWorkerException: TOTPUnhandledWorkerException read
GetAsy_OnUnhandledWorkerException write SetAsy_OnUnhandledWorkerException;
property Affinity: IOmniIntegerSet read GetAffinity;
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 NumCores: integer read GetNumCores;
property Options: TOmniThreadPoolOptions read GetOptions write SetOptions;
property UniqueID: int64 read GetUniqueID;
property WaitOnTerminate_sec: integer read GetWaitOnTerminate_sec write
SetWaitOnTerminate_sec;
{$IFDEF OTL_NUMASupport}
property ProcessorGroups: IOmniIntegerSet read GetProcessorGroups write
SetProcessorGroups;
property NUMANodes: IOmniIntegerSet read GetNUMANodes write SetNUMANodes;
{$ENDIF OTL_NUMASupport}
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);
SendPoolNotifications(pntCreate, Result);
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(signalCancellationToken: boolean);
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 begin
if signalCancellationToken then
task.CancellationToken.Signal;
task.Terminate;
end;
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
try
Comm.Send(MSG_THREAD_CREATED, threadID);
try
if owtThreadDataFactory.IsEmpty then
owtThreadData := nil
else try
owtThreadData := owtThreadDataFactory.Execute;
except
owtThreadData := nil;
end;
while GetMsg(msg) do 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; // while GetMsg
try
owtThreadData := nil;
except
end;
finally Comm.Send(MSG_THREAD_DESTROYING, threadID); end;
except
on E: Exception do
if assigned(owtAsy_OnUnhandledException) then
owtAsy_OnUnhandledException(Self, E);
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
Environment.Thread.GroupAffinity := workItem.GroupAffinity;
{$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;
end; { TOTPWorkerThread.ExecuteWorkItem }
function TOTPWorkerThread.GetMsg(var msg: TOmniMessage): boolean;
begin
Result := Comm.ReceiveWait(msg, 100);
if not Result then begin
SetThreadName('Idle thread worker');
Result := Comm.ReceiveWait(msg, INFINITE);
end;
end; { TOTPWorkerThread.GetMsg }
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;
MaxExecuting.Value := Environment.Process.Affinity.Count;
NumCores.Value := MaxExecuting.Value;
IdleWorkerThreadTimeout_sec.Value := CDefaultIdleWorkerThreadTimeout_sec;
WaitOnTerminate_sec.Value := CDefaultWaitOnTerminate_sec;
end; { TOTPWorker.Create }
function TOTPWorker.ActiveWorkItemDescriptions: string;
var
description : string;
iWorker : integer;
sbDescriptions: TStringBuilder;
ScheduledAt : TDateTime;
StartedAt : TDateTime;