forked from gabr42/OmniThreadLibrary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOtl.Parallel.Tasks.pas
2932 lines (2538 loc) · 82.8 KB
/
Otl.Parallel.Tasks.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
unit Otl.Parallel.Tasks;
{$I OtlOptions.inc}
interface
uses Otl.Parallel.Extras, System.Classes, Otl.Parallel.Pipe,
System.Generics.Collections,
System.SysUtils, System.SyncObjs,
Otl.Parallel.SynchroPrimitives.InterfaceLevel,
Otl.Parallel.SynchroPrimitives.ModularLevel
// Ensure that Atomic is last in the uses list, so that its record
// helpers (in the case of NDEF USE_SLACKSPACE_ALIGNMENT) are in scope.
, Otl.Parallel.Atomic
;
type
/// <remarks>This is an internal class. Do not use.</remarks>
TTasking = class
class function CreateWorkFactory(
MaxThreadCount1, MinIdleCount1, MaxIdleCount1, MaxEventPool: integer;
const SharedLock: ILock = nil): IWorkFactory;
class function CreateFuture<T>( const AFactory: IWorkFactory; Func: TFutureFunc<T>): IFuture<T>;
class function Join( const WorkFactory: IWorkFactory; const Tasks: array of ITask): ITask;
end;
TTaskThreadStatus = (ttsIdle, ttsInWork, ttsTerminated);
TWorkFactory = class;
TTaskThread = class( TThread)
private const
TaskQueueTimeOutPeriod = 10000; // 10 s
private
function GetStatus: TTaskThreadStatus;
procedure SetStatus( Value: TTaskThreadStatus);
function IsLocallyTerminated: boolean;
function IsGloballyTerminated: boolean;
function IsTerminated: boolean;
protected
FWorkFactory: TWorkFactory;
FLock: ILock;
[Volatile] FStatus: TVolatileUint32; // (TTaskThreadStatus
[Volatile] FisTerminated: TVolatileUint32;
FHouseKeeperAlert: IEvent; // Shared. Auto-reset.
FWorkAlert: IEvent; // Shared. Auto-reset
procedure Execute; override;
public
constructor Create( AOwner: TWorkFactory);
destructor Destroy; override;
property Status: TTaskThreadStatus read GetStatus write SetStatus;
end;
ITaskEx = interface;
TJobPipe = class( TPipe<ITaskEx>) end;
RSchedJob = record
FMaturity: TDateTime;
FJob: ITaskEx;
end;
TSchedQueue = class( TList<RSchedJob>)
public
constructor Create;
function OrderedAdd( const Addend: RSchedJob): integer;
function PopMature( NowTime: TDateTime; var PopJob: ITaskEx): boolean;
function NextMaturity( var Value: TDateTime): boolean;
end;
THouseKeeperThread = class( TThread)
public
const HouseKeepingPeriod = 1000; // ms
private
FWorkFactory: TWorkFactory;
FLock: ILock;
FHouseKeeperAlert: IEvent; // Shared. Auto-reset.
FWorkAlert: IEvent; // Shared. Auto-reset
[Volatile] FisTerminated: TVolatileUint32;
FAllThreadsDone: ICountDown;
FMaxThreadCount: cardinal; // Maximum allowable count of threads.
FMinIdleCount: cardinal; // Minimum count of idle threads that the house-keeper is to maintain, if permitted by Max properties.
FMaxIdleCount: cardinal; // Maximum count of idle threads that the house-keeper is to maintain.
procedure ComputeHowManyNewThreadsToCreate( var More: boolean; var Delta: integer);
protected
procedure Execute; override;
public
constructor Create( AOwner: TWorkFactory);
destructor Destroy; override;
end;
TTask = class;
TBaseFuture = class;
TBaseFutureClass = class of TBaseFuture;
TComputeFutureProc = reference to procedure( const Task: TBaseFuture);
{$REGION 'Private declarations - do not use'}
// These are in the interface section due to the limitations of generics.
TCoForEachTaskFactory = class abstract
private
FTemplate : ITask;
public
FCompositeTask: ITask;
constructor Create( WF: TWorkFactory; ThreadCount: integer);
function CreateTemplate ( WF: TWorkFactory ): ITask; virtual; abstract;
function CreateCompositeTask( WF: TWorkFactory; const Iterators: array of ITask): ITask; virtual;
end;
TTaskFactFunc = reference to function( AWF: TWorkFactory; AIntVal: integer): TCoForEachTaskFactory;
{$ENDREGION}
TWorkFactory = class( TInterfacedObject, IWorkFactory)
public const
MaxCoForEachThreadCount = 10;
private
FLock: ILock;
[Volatile] FThreadCount: TVolatileUint32; // Total number of threads either in-work, terminated or idle.
[Volatile] FIdleCount: TVolatileUint32; // Count of idle threads available for tasking.
FMaxThreadCount: cardinal; // Maximum allowable count of threads.
FMinIdleCount: cardinal; // Minimum count of idle threads that the house-keeper is to maintain, if permitted by Max properties.
FMaxIdleCount: cardinal; // Maximum count of idle threads that the house-keeper is to maintain.
[Volatile] FisTerminated: TVolatileUint32;
[Volatile] FWorkEnqueued: TVolatileUint32;
[Volatile] FWorkCapacity: TVolatileUint32;
FTaskQueue: TJobPipe;
FReturnQueue: TJobPipe;
FTaskThreads: TObjectList<TTaskThread>;
FHouseKeepAlert: IEvent; // Auto-reset
FWorkAlert: IEvent; // Auto-reset
FHouseKeeper: THouseKeeperThread;
FShareLock: ILock;
FSynchroPool: TSynchroFactory;
FAllThreadsDone: ICountDown;
FSchedQueue: TSchedQueue;
function FactoryLock: ILock;
function AsObject: TObject;
function ProcessJobReturn( TimeOut: cardinal): boolean;
function QueueJob( const Task: ITask): boolean;
procedure SchedQueueJob( AMaturity: TDateTime; const Task: ITaskEx);
procedure StartTask( const TaskIntf: ITask);
function CanStart( TaskObj: TTask): boolean;
function NewLock( Locking: TLockingMechanism): ILock;
function Event ( ManualReset, InitialState: boolean): IEvent; // Interface level, Reusable.
function LightEvent ( ManualReset, InitialState: boolean; SpinMax: cardinal): IEvent; // Interface level, Reusable.
function CountDown( InitialValue: cardinal): ICountDown; // Interface level, Reusable.
function CompositeSynchro_WaitAll( const AFactors: TSynchroArray; APropagation: TWaitPropagation): ICompositeSynchro;
function CompositeSynchro_WaitAny( const AFactors: TSynchroArray; APropagation: TWaitPropagation): ICompositeSynchro;
function ModularEvent ( ManualReset, InitialState: boolean): IEvent; overload;
function ModularEvent ( const ABase: IEvent ): IEvent; overload;
function ModularSemaphore( AInitialCount: cardinal): ISemaphore; overload;
function ModularSemaphore( const ABase: ISemaphore): ISemaphore; overload;
function ModularCountDown( AInitialValue: cardinal): ICountDown; overload;
function ModularCountDown( const ABase: ICountDown): ICountDown; overload;
function Join( const Tasks: array of ITask ): ITask; overload;
function Join( const Procs: array of System.SysUtils.TProc): ITask; overload;
function Join( const Procs: array of TTaskProc ): ITask; overload;
function WaitForAny( const AFactors: TSynchroArray; APropagation: TWaitPropagation; var SignallerIdx: integer; TimeOut: cardinal = FOREVER): TWaitResult;
function WaitForAll( const AFactors: TSynchroArray; APropagation: TWaitPropagation; TimeOut: cardinal = FOREVER): TWaitResult;
function CoForEach( LowIdx, HighIdx, StepIdx: integer; ThreadCount: integer; Proc: TForEachProc): ITask; overload;
function CoForEachBase( ThreadCount: integer; TaskFact: TTaskFactFunc): ITask;
function Abandonable( const BaseTask: ITask; Timeout: integer): IFuture<boolean>;
procedure AbandonTask( const Task: ITask);
function GeometricRetry( BaseFunc: TFutureFunc<boolean>; InitialRetryPause: integer; PauseGrowth: double; MaxRetryPause: integer; MaxTryCount: integer): IFuture<boolean>;
function SelfJoin( const BaseTask: ITask; ThreadCount: integer): ITask;
public
/// <remarks> DO NOT USE. This constructor is for internal use only.
/// Use instead either TSBDParallel.CreateWorkFactory. </remarks>
constructor CreateWorkFactory( MaxThreadCount1, MinIdleCount1, MaxIdleCount1, MaxEventCount1: integer; const SharedLock: ILock = nil);
destructor Destroy; override;
function CoBeginTask( Proc: System.SysUtils.TProc): ITask; overload;
function CoBeginTask( Proc: TTaskProc ): ITask; overload;
function CoForEach<T>( Collection: IEnumerable<T>; CollectionCursorIsThreadSafe: boolean; ThreadCount: integer; Proc: TForEachItemProc<T>): ITask; overload;
function CoForEach<T>( Collection: TEnumerable<T>; CollectionCursorIsThreadSafe: boolean; ThreadCount: integer; Proc: TForEachItemProc<T>): ITask; overload;
function ShareLock: ILock;
function SynchroPool: TSynchroFactory;
end;
ITaskEx = interface ['{BF5FF699-E6E0-4993-BB16-C623D122E781}']
function GetStatus: TTaskStatus;
procedure SetStatus( Value: TTaskStatus);
procedure BeforeExecute;
procedure Execute;
procedure ReleaseExecuteProc;
procedure AfterExecute;
procedure ExecuteReturn;
procedure MarkExceptionThrown;
function DoCaptureException: boolean;
procedure Clear;
function QueueIfCan: boolean;
procedure Signal;
procedure DereferenceParent;
procedure AddChild( const Addend: ITaskEx);
procedure AddChildren( const Addends: array of ITaskEx);
procedure EndAddingChildren;
procedure QueueChildren;
procedure SetParent( const ATask: TTask);
procedure CleanUpAfterDoneOrCancelled;
procedure AttachThread( AThread: TTaskThread);
procedure DetachThread;
function AttachedThread: TTaskThread;
property Status: TTaskStatus read GetStatus write SetStatus;
end;
TTask = class( TInterfacedObject, ITask, ITaskEx)
private
[Volatile] FStatus: TVolatileUint32;
[Volatile] FDatum: TVolatileObject;
[Volatile] FAttachedThread: TVolatileObject;
FWorkFactory: TWorkFactory;
FJob: TTaskProc;
FReturnJob: TTaskProc;
FhasThrownException: boolean;
FParent: TTask;
FParentLock: TSBDSpinLock;
FChildrenTasks: TArray<ITaskEx>;
FTermination: ICountDown;
function AsObject: TObject;
function Queue: ITask;
function CanStart: boolean;
function QueueIfCan: boolean;
procedure SetFinalStatus( Value: TTaskStatus);
procedure SetParent( const ATask: TTask);
procedure AttachThread( AThread: TTaskThread);
procedure DetachThread;
function AttachedThread: TTaskThread;
protected
function GetDatum: TObject; virtual;
procedure SetDatum( Value: TObject); virtual;
function GetStatus: TTaskStatus; virtual;
function ITask.Status = GetStatus;
procedure SetStatus( Value: TTaskStatus); virtual;
function IsDone: boolean; virtual;
function SetOnDone( Proc: TTaskProc): ITask; virtual;
function FundamentalClone: TTask; virtual;
function Clone: ITask; virtual;
procedure DereferenceParent; virtual;
procedure AddChildren( const Addends: array of ITaskEx); virtual;
procedure EndAddingChildren; virtual;
procedure AddChild( const Addend: ITaskEx); virtual;
procedure Signal; virtual;
procedure BeforeExecute; virtual;
procedure Execute; virtual;
procedure ReleaseExecuteProc; virtual;
procedure AfterExecute; virtual;
procedure ExecuteReturn; virtual;
procedure MarkExceptionThrown; virtual;
function DoCaptureException: boolean; virtual;
procedure Clear; virtual;
procedure Cancel; virtual;
function TerminationSynchro: ISynchro; virtual;
procedure QueueChildren; virtual;
procedure CleanUpAfterDoneOrCancelled; virtual;
function TaskLoad: integer; virtual;
public
constructor Create( AWorkFactory: TWorkFactory; AJob: TTaskProc; AParent: TTask); virtual;
destructor Destroy; override;
end;
TTaskClass = class of TTask;
TDecoratedTask = class( TTask)
protected
FBase: ITaskEx;
function GetDatum: TObject; override;
procedure SetDatum( Value: TObject); override;
function GetStatus: TTaskStatus; override;
procedure SetStatus( Value: TTaskStatus); override;
function IsDone: boolean; override;
function SetOnDone( Proc: TTaskProc): ITask; override;
function Clone: ITask; override;
procedure DereferenceParent; override;
procedure AddChildren( const Addends: array of ITaskEx); override;
procedure EndAddingChildren; override;
procedure AddChild( const Addend: ITaskEx); override;
procedure Signal; override;
procedure BeforeExecute; override;
procedure Execute; override;
procedure ReleaseExecuteProc; override;
procedure AfterExecute; override;
procedure ExecuteReturn; override;
procedure MarkExceptionThrown; override;
function DoCaptureException: boolean; override;
procedure Clear; override;
procedure Cancel; override;
function TerminationSynchro: ISynchro; override;
procedure CleanUpAfterDoneOrCancelled; override;
public
constructor CreateDecorated( AWorkFactory: TWorkFactory; const ABase: ITaskEx);
destructor Destroy; override;
end;
TBaseFuture = class abstract( TTask)
protected
FCapturedException: Exception;
FReturnLock: TSBDSpinLock;
function AsIFuture: IInterface; virtual; abstract;
public
constructor Create( AWorkFactory: TWorkFactory; AJob: TTaskProc; AParent: TTask); override;
destructor Destroy; override;
end;
{$WARN HIDDEN_VIRTUAL OFF}
// Suppressed Warning: SetOnDone() hides vmethod of base type.
TFuture<T> = class( TBaseFuture, IFuture<T>)
private
FValue: T;
FFunc: TFutureFunc<T>;
FDoneProc: TProcessValueProc<T>;
function QueueFuture: IFuture<T>;
function TryValue( var Value: T; TimeOut: cardinal = FOREVER): boolean;
function SetOnDone( OnDoneProc: TProcessValueProc<T>): IFuture<T>; overload;
function GetValue: T;
function GetReturnAction( var ReturnProc: TProcessValueProc<T>; var PropagatedException: Exception): boolean;
procedure ComputeValueOrCaptureException( Task: TBaseFuture);
procedure CallReturnProcOrPropageException( Task: TBaseFuture);
protected
function AsIFuture: IInterface; override;
procedure ReleaseExecuteProc; override;
procedure Clear; override;
procedure Execute; override;
procedure ExecuteReturn; override;
function FundamentalClone: TTask; override;
public
constructor Create( AWorkFactory: TWorkFactory; AFunc: TFutureFunc<T>; AParent: TTask); virtual;
destructor Destroy; override;
end;
{$WARN HIDDEN_VIRTUAL ON}
TFutureBoolean = class( TFuture<boolean>) end;
TJoinTask = class( TTask)
public
constructor CreateJoin( AWorkFactory: TWorkFactory; const ATasks: array of ITask);
protected
procedure Execute; override;
procedure Cancel; override;
end;
TJoinIntegerTask = class( TJoinTask)
public
[Volatile] FValue: TVolatileInt32;
constructor CreateIntegerJoin( AWorkFactory: TWorkFactory; const ATasks: array of ITask; InitialValue: integer);
protected
procedure CleanUpAfterDoneOrCancelled; override;
end;
TJoinObjectOwningTask = class( TJoinTask)
private
FObj: TObject;
public
constructor CreateObjectJoin( AWorkFactory: TWorkFactory; const ATasks: array of ITask; AObj: TObject);
destructor Destroy; override;
protected
procedure CleanUpAfterDoneOrCancelled; override;
end;
TValuePipelineBase = class abstract( TInterfacedObject, IValuePipelineBase)
protected
procedure Start; virtual; abstract;
end;
TStageTaskFactory = reference to function( AFactory: TWorkFactory; Stage: TObject) : ITask;
TValuePipeline<T> = class( TValuePipelineBase, IValuePipeline<T>)
private type
TStage<U> = class
private
FPipeline: TValuePipeline<U>;
FIdx: integer;
FStagerTasks: TList<ITask>;
FInData: IPipe<U>;
FOutData: IPipe<U>;
[Volatile] FIncompleteCount: TVolatileUint32;
procedure Start;
constructor CreateStage( AOwner: TValuePipeline<U>; StageTaskFactory: TStageTaskFactory; Capacity, LowWaterMark, HighWaterMark, ThreadCount: cardinal);
public
constructor CreateStageFromSingleFunc( AOwner: TValuePipeline<U>; StageTask: TSingleFunc<U>; Capacity, LowWaterMark, HighWaterMark, ThreadCount: cardinal);
constructor CreateStageFromPipeToPipe( AOwner: TValuePipeline<U>; StageTask: TPipeToPipe<U>; Capacity, LowWaterMark, HighWaterMark, ThreadCount: cardinal);
destructor Destroy; override;
end;
private type
TSingleFuncStager<U> = class( TTask)
private
FStageFunc: TSingleFunc<U>;
FInData, FOutData: IPipe<U>;
FStage: TStage<U>;
protected
procedure Execute; override;
procedure ReleaseExecuteProc; override;
procedure Clear; override;
public
constructor CreateSingleStager( AFactory: TWorkFactory; AStage: TStage<U>; StageTask: TSingleFunc<U>; const AInData, AOutData: IPipe<U>);
end;
TPipeToPipeStager<U> = class( TTask)
private
FStageFunc: TPipeToPipe<U>;
FInData, FOutData: IPipe<U>;
FStage: TStage<U>;
protected
procedure Execute; override;
procedure ReleaseExecuteProc; override;
procedure Clear; override;
public
constructor CreatePipeStager( AFactory: TWorkFactory; AStage: TStage<U>; StageTask: TPipeToPipe<U>; const AInData, AOutData: IPipe<U>);
end;
private
FFactory: TWorkFactory;
FInputQueue: IPipe<T>;
FOutputQueue: IPipe<T>;
FStages: TObjectList<TStage<T>>;
function InputQueue: IPipe<T>;
function OutputQueue: IPipe<T>;
function Stage( StageTask: TSingleFunc<T>; Capacity, LowWaterMark, HighWaterMark, ThreadCount: cardinal): IValuePipeline<T>; overload;
function Stage( StageTask: TPipeToPipe<T>; Capacity, LowWaterMark, HighWaterMark, ThreadCount: cardinal): IValuePipeline<T>; overload;
protected
procedure Start; override;
public
constructor Create( AFactory: TWorkFactory; Capacity, LowWaterMark, HighWaterMark: cardinal);
destructor Destroy; override;
end;
TForkJoin<T> = class( TFuture<T>)
private type
TForkJoinProblemStatus = (UntestedHolistic, ForkableHolistic, InWorkForked, JoinableForked, Solved);
private type
TProc_Bool = reference to procedure( Value: boolean);
private type
TForkJoinProblem = class;
IForkJoinProblem = interface ['{81B15F6C-C47B-4A31-86BD-CE06BD182D00}']
function AsObject: TObject;
end;
TForkJoinProblem = class( TInterfacedObject, IForkJoinProblem)
private
function AsObject: TObject;
public
FStatus: TForkJoinProblemStatus;
FDatum: T; // Default(T) when forked.
FChildren: TArray<IForkJoinProblem>; // The array is empty when holistic or solved.
FCountOfUnsolvedChildren: cardinal; // only can be non-zero when ForkedWithUnsolvedChildren, then it is 1+
FForkParent: TForkJoinProblem; // nil when it is the seed.
constructor Create( AStatus: TForkJoinProblemStatus; const ADatum: T; AForkParent: TForkJoinProblem);
end;
private type
TProblemStack = class( TStack<IForkJoinProblem>)
end;
private type
TForkJoiner = class( TTask)
private
FOwner: TForkJoin<T>;
protected
procedure Execute; override;
public
constructor CreateForker( AOwner: TForkJoin<T>);
end;
private
FDoFork: TTestFunc<T>;
FFork : TForkFunc<T>;
FJoin : TJoinFunc<T>;
FSeed : IForkJoinProblem; // Seed is the root problem
FJoinStack: TProblemStack;
FForkStack: TProblemStack;
FTestStack: TProblemStack;
FhasCancelled: boolean;
[Volatile] FCapturedException: TVolatileObject; // Exception
FActionable: TEvent; // manual-reset event.
FUnfinishedChildTasks: ICountDown;
FIsActionable: boolean;
FCountOfProblemsInWork: integer;
FQueueLock: TSBDSpinLock;
function Act( Action: TForkJoinerAction; Problem: TForkJoinProblem; EnterLockProc: TProc_Bool): boolean;
function Test( Problem: TForkJoinProblem; EnterLockProc: TProc_Bool): boolean;
function Fork( Problem: TForkJoinProblem; EnterLockProc: TProc_Bool): boolean;
function Join( Problem: TForkJoinProblem; EnterLockProc: TProc_Bool): boolean;
procedure MarkAsSolved( Problem: TForkJoinProblem; EnterLockProc: TProc_Bool);
public
constructor CreateForkJoin( const AFactory: TWorkFactory; const ASeed: T; NumTasks: cardinal; ADoFork: TTestFunc<T>; AFork: TForkFunc<T>; AJoin: TJoinFunc<T>);
destructor Destroy; override;
end;
{$REGION 'Private declarations - do not use'}
// These are in the interface section due to the limitations of generics.
TCoForEachIntegerTaskFactory = class sealed( TCoForEachTaskFactory)
public
constructor Create( WF: TWorkFactory; ThreadCount: integer; LowIdx, HighIdx, StepIdx: integer; Proc: TForEachProc);
function CreateTemplate ( WF: TWorkFactory ): ITask; override;
function CreateCompositeTask( WF: TWorkFactory; const Iterators: array of ITask): ITask; override;
protected
FLowIdx: integer;
FHighIdx: integer;
FStepIdx: integer;
FCompositeTaskObj: TJoinIntegerTask;
FProc: TForEachProc;
end;
TCoForEachEnumerableTaskFactory<T> = class abstract( TCoForEachTaskFactory)
public
constructor Create( WF: TWorkFactory; ThreadCount: integer; CollectionCursorIsThreadSafe: boolean; Proc: TForEachItemProc<T>);
protected
FIsThreadSafe: boolean;
FProc : TForEachItemProc<T>;
FCursorLock : ILock;
end;
TCoForEachEnumerableObjTaskFactory<T> = class sealed( TCoForEachEnumerableTaskFactory<T>)
public
constructor Create( WF: TWorkFactory; ThreadCount: integer; Collection: TEnumerable<T>; CollectionCursorIsThreadSafe: boolean; Proc: TForEachItemProc<T>);
function CreateTemplate( WF: TWorkFactory): ITask; override;
function CreateCompositeTask( WF: TWorkFactory; const Iterators: array of ITask): ITask; override;
protected
FCursor: TEnumerator<T>;
end;
TCoForEachEnumerableIntfTaskFactory<T> = class sealed( TCoForEachEnumerableTaskFactory<T>)
public
constructor Create( WF: TWorkFactory; ThreadCount: integer; Collection: IEnumerable<T>; CollectionCursorIsThreadSafe: boolean; Proc: TForEachItemProc<T>);
function CreateTemplate( WF: TWorkFactory): ITask; override;
protected
FCursor: IEnumerator<T>;
end;
procedure EnterLock( var SpinLock: TSBDSpinLock; var EnteredFlag: boolean; Value: boolean);
{$ENDREGION}
implementation
uses System.Types, System.Generics.Defaults;
type
TSchedJobComparer = class( TInterfacedObject, IComparer<RSchedJob>)
private
function Compare( const Left, Right: RSchedJob): integer;
end;
IGeometricFuture = interface ['{41093AE2-0EA2-4044-AAD2-233A30D02DE9}'] end;
TGeometricFuture = class( TFuture<boolean>, IGeometricFuture)
protected
function TaskLoad: integer; override;
function FundamentalClone: TTask; override;
public
FTrialIndex: integer;
FPause : integer;
FGrowth : double;
FMaxPause: integer;
FTryCount: integer;
constructor CreateGeo( AWorkFactory: TWorkFactory; AFunc: TFutureFunc<boolean>;
AInitialRetryPause: integer; APauseGrowth: double; AMaxRetryPause, AMaxTryCount: integer);
procedure IncrementTryCount;
function MaxedOut: boolean;
procedure BumpPausePeriod;
function NextTrialMatures: TDateTime;
end;
constructor TWorkFactory.CreateWorkFactory(
MaxThreadCount1, MinIdleCount1, MaxIdleCount1, MaxEventCount1: integer; const SharedLock: ILock);
var
Capacity: integer;
begin
//SiAuto.SiMain
FSynchroPool := TSynchroFactory.Create( MaxEventCount1);
FLock := TSynchroFactory.AcquireCriticalSection;
FShareLock := SharedLock;
if not assigned( FShareLock) then
FShareLock := TSynchroFactory.AcquireCriticalSection;
FThreadCount .Initialize(0);
FIdleCount .Initialize(0);
FisTerminated.Initialize( 0);
FWorkEnqueued.Initialize( 0);
FMaxThreadCount := MaxThreadCount1;
if FMaxThreadCount = 0 then
FMaxThreadCount := 1;
Capacity := FMaxThreadCount * 2;
FTaskQueue := TJobPipe.Create( self, Capacity-1, 1, Capacity);
FTaskQueue._AddRef;
FSchedQueue := TSchedQueue.Create;
FMaxIdleCount := MaxIdleCount1;
if FMaxIdleCount >= FMaxThreadCount then
FMaxIdleCount := FMaxThreadCount - 1;
FMinIdleCount := MinIdleCount1;
if FMinIdleCount > FMaxIdleCount then
FMinIdleCount := FMaxIdleCount;
FTaskThreads := TObjectList<TTaskThread>.Create( False);
FReturnQueue := TJobPipe.Create( self, Capacity-1, 1, Capacity);
FReturnQueue._AddRef;
FWorkCapacity.Initialize( FMaxThreadCount);
FHouseKeepAlert := TSBDParallel.Event( False, False);
FWorkAlert := TSBDParallel.Event( False, False);
FAllThreadsDone := FSynchroPool.AcquireCountDown( 1, False);
FHouseKeeper := THouseKeeperThread.Create( self)
end;
destructor TWorkFactory.Destroy;
begin
FLock.Enter;
FisTerminated.Write( 1);
if assigned( FHouseKeeper) then
FHouseKeeper.FisTerminated.Write( 1);
FWorkAlert.Signal;
FTaskQueue.Complete;
FReturnQueue.Complete;
FLock.Leave;
FAllThreadsDone.WaitFor;
FAllThreadsDone := nil;
FTaskQueue._Release;
FReturnQueue._Release;
FTaskThreads.Free;
FSchedQueue.Free;
FLock := nil;
if FSynchroPool.CanDestroy then
FSynchroPool.Free
else
raise Exception.Create( 'Allocated locks must be all released before TWorkFactory is destroyed.');
inherited
end;
function TWorkFactory.Abandonable(
const BaseTask: ITask; Timeout: integer): IFuture<boolean>;
begin
result := TTasking.CreateFuture<boolean>( self,
function( const Future: IFuture<boolean>): boolean
begin
result := BaseTask.Queue.TerminationSynchro.WaitFor( Timeout) = wrSignaled;
if not result then
AbandonTask( BaseTask)
end)
end;
procedure TWorkFactory.AbandonTask( const Task: ITask);
var
Thread: TTaskThread;
begin
Task.Cancel;
FLock.Enter;
Thread := (Task as ITaskEx).AttachedThread;
if Thread.Status = ttsInWork then
Thread.Status := ttsTerminated;
FLock.Leave
end;
function TWorkFactory.AsObject: TObject;
begin
result := self
end;
function TWorkFactory.CountDown( InitialValue: cardinal): ICountDown;
begin
result := FSynchroPool.AcquireCountDown( InitialValue, True)
end;
function TWorkFactory.Event( ManualReset, InitialState: boolean): IEvent;
begin
result := FSynchroPool.AcquireKernelEvent( ManualReset, InitialState, True)
end;
function TWorkFactory.LightEvent(
ManualReset, InitialState: boolean; SpinMax: cardinal): IEvent;
begin
result := FSynchroPool.AcquireLightEvent( ManualReset, InitialState, SpinMax, True)
end;
function TWorkFactory.CanStart( TaskObj: TTask): boolean;
begin
FLock.Enter;
result := (FisTerminated.Read = 0) and
(TaskObj.GetStatus = tsConfigurable) and
(FWorkCapacity.Read > 0);
FLock.Leave
end;
function TWorkFactory.CoBeginTask( Proc: TTaskProc): ITask;
var
Task: TTask;
begin
Task := TTask.Create( self, Proc, nil);
Task.EndAddingChildren;
result := Task
end;
constructor TCoForEachTaskFactory.Create( WF: TWorkFactory; ThreadCount: integer);
var
Iterators: array of ITask;
IteratorCount: integer;
i: integer;
begin
FTemplate := CreateTemplate( WF);
IteratorCount := ThreadCount;
if IteratorCount < 1 then
IteratorCount := 1;
if IteratorCount > TWorkFactory.MaxCoForEachThreadCount then
IteratorCount := TWorkFactory.MaxCoForEachThreadCount;
SetLength( Iterators, IteratorCount);
Iterators[0] := FTemplate;
for i := 1 to IteratorCount - 1 do
Iterators[i] := FTemplate.Clone;
FCompositeTask := CreateCompositeTask( WF, Iterators)
end;
function TCoForEachTaskFactory.CreateCompositeTask(
WF: TWorkFactory; const Iterators: array of ITask): ITask;
begin
result := TJoinTask.CreateJoin( WF, Iterators)
end;
constructor TCoForEachEnumerableIntfTaskFactory<T>.Create(WF: TWorkFactory;
ThreadCount: integer; Collection: IEnumerable<T>;
CollectionCursorIsThreadSafe: boolean; Proc: TForEachItemProc<T>);
begin
FCursor := Collection.GetEnumerator;
inherited Create( WF, ThreadCount, CollectionCursorIsThreadSafe, Proc)
end;
function TCoForEachEnumerableIntfTaskFactory<T>.CreateTemplate(
WF: TWorkFactory): ITask;
begin
if FIsThreadSafe then
result := WF.CoBeginTask(
procedure( const Task: ITask)
begin
while FCursor.MoveNext do
FProc( FCursor.Current, FCompositeTask)
end)
else
result := WF.CoBeginTask(
procedure( const Task: ITask)
var
doMoveNext: boolean;
Current : T;
begin
repeat
FCursorLock.Enter;
doMoveNext := FCursor.MoveNext;
if doMoveNext then
Current := FCursor.Current
else
Current := Default( T);
FCursorLock.Leave;
if doMoveNext then
FProc( Current, FCompositeTask)
until not doMoveNext
end)
end;
constructor TCoForEachIntegerTaskFactory.Create( WF: TWorkFactory; ThreadCount: integer; LowIdx, HighIdx, StepIdx: integer; Proc: TForEachProc);
begin
FLowIdx := LowIdx;
FHighIdx := HighIdx;
FStepIdx := StepIdx;
FProc := Proc;
FCompositeTaskObj := nil;
// FCompositeTaskObj is created later.
inherited Create( WF, ThreadCount)
end;
function TCoForEachIntegerTaskFactory.CreateTemplate( WF: TWorkFactory): ITask;
begin
result := WF.CoBeginTask(
procedure( const Task: ITask)
var
OldValue, NewValue: integer;
function IsWithinRange( IndexValue: integer): boolean;
begin
// If StepIdx is +ve, HighIdx is an upper bound.
// If StepIdx is -ve, HighIdx is an lower bound.
// If StepIdx is zero (edge case), we shouldn't do any iteration.
result := ((IndexValue <= FHighIdx) and (FStepIdx > 0)) or
((IndexValue >= FHighIdx) and (FStepIdx < 0))
end;
begin
repeat
NewValue := FCompositeTaskObj.FValue.Add( FStepIdx);
OldValue := NewValue - FStepIdx;
if ((NewValue < OldValue) and (FStepIdx > 0)) or
((NewValue > OldValue) and (FStepIdx < 0)) then
// This can only occur if there is an integer overflow.
// If it is an overflow, it is time to cease iteration.
// This should be a rare edge case.
break;
if IsWithinRange( OldValue) then
FProc( OldValue, FCompositeTask)
until not IsWithinRange( NewValue)
end);
end;
function TCoForEachIntegerTaskFactory.CreateCompositeTask( WF: TWorkFactory; const Iterators: array of ITask): ITask;
begin
FCompositeTaskObj := TJoinIntegerTask.CreateIntegerJoin( WF, Iterators, FLowIdx);
result := FCompositeTaskObj
end;
constructor TCoForEachEnumerableTaskFactory<T>.Create(WF: TWorkFactory;
ThreadCount: integer; CollectionCursorIsThreadSafe: boolean;
Proc: TForEachItemProc<T>);
begin
FIsThreadSafe := CollectionCursorIsThreadSafe;
FProc := Proc;
if not FIsThreadSafe then
FCursorLock := WF.NewLock( KernalLocking);
inherited Create( WF, ThreadCount)
end;
constructor TCoForEachEnumerableObjTaskFactory<T>.Create( WF: TWorkFactory; ThreadCount: integer; Collection: TEnumerable<T>; CollectionCursorIsThreadSafe: boolean; Proc: TForEachItemProc<T>);
begin
FCursor := Collection.GetEnumerator;
inherited Create( WF, ThreadCount, CollectionCursorIsThreadSafe, Proc)
end;
function TCoForEachEnumerableObjTaskFactory<T>.CreateCompositeTask(
WF: TWorkFactory; const Iterators: array of ITask): ITask;
begin
result := TJoinObjectOwningTask.CreateObjectJoin( WF, Iterators, FCursor)
// The task owns the cursor object, and will destroy it when it cleans up.
end;
function TCoForEachEnumerableObjTaskFactory<T>.CreateTemplate( WF: TWorkFactory): ITask;
begin
if FIsThreadSafe then
result := WF.CoBeginTask(
procedure( const Task: ITask)
begin
while FCursor.MoveNext do
FProc( FCursor.Current, FCompositeTask)
end)
else
result := WF.CoBeginTask(
procedure( const Task: ITask)
var
doMoveNext: boolean;
Current : T;
begin
repeat
FCursorLock.Enter;
doMoveNext := FCursor.MoveNext;
if doMoveNext then
Current := FCursor.Current
else
Current := Default( T);
FCursorLock.Leave;
if doMoveNext then
FProc( Current, FCompositeTask)
until not doMoveNext
end)
end;
function TWorkFactory.CoForEachBase( ThreadCount: integer; TaskFact: TTaskFactFunc): ITask;
var
Factory: TCoForEachTaskFactory;
begin
Factory := TaskFact( self, ThreadCount);
try
result := Factory.FCompositeTask
finally
Factory.Free;
end
end;
function TWorkFactory.CoForEach(
LowIdx, HighIdx, StepIdx, ThreadCount: integer; Proc: TForEachProc): ITask;
begin
result := CoForEachBase( ThreadCount,
function( AWF: TWorkFactory; AThreadCount: integer): TCoForEachTaskFactory
begin
result := TCoForEachIntegerTaskFactory.Create( AWF, AThreadCount, LowIdx, HighIdx, StepIdx, Proc)
end)
end;
function TWorkFactory.CoForEach<T>(
Collection: TEnumerable<T>; CollectionCursorIsThreadSafe: boolean; ThreadCount: integer; Proc: TForEachItemProc<T>): ITask;
begin
result := CoForEachBase( ThreadCount,
function( AWF: TWorkFactory; AThreadCount: integer): TCoForEachTaskFactory
begin
result := TCoForEachEnumerableObjTaskFactory<T>.Create( self, ThreadCount, Collection, CollectionCursorIsThreadSafe, Proc)
end)
end;
function TWorkFactory.CoForEach<T>(
Collection: IEnumerable<T>; CollectionCursorIsThreadSafe: boolean; ThreadCount: integer;
Proc: TForEachItemProc<T>): ITask;
begin
result := CoForEachBase( ThreadCount,
function( AWF: TWorkFactory; AThreadCount: integer): TCoForEachTaskFactory
begin
result := TCoForEachEnumerableIntfTaskFactory<T>.Create( self, ThreadCount, Collection, CollectionCursorIsThreadSafe, Proc)
end)
end;
function TWorkFactory.CoBeginTask( Proc: System.SysUtils.TProc): ITask;
begin
result := CoBeginTask(
procedure( const Task: ITask)
begin
Proc();
end)
end;
function TWorkFactory.QueueJob( const Task: ITask): boolean;
var
willEnqueue, hasEnqueued: boolean;
doHouseKeep: boolean;
TaskEx: ITaskEx;
begin
result := True;
if not Supports( Task, ITaskEx, TaskEx) then
TaskEx := nil;
if not assigned( TaskEx) then
raise Exception.Create( 'TWorkFactory.StartTask() - no task.');
doHouseKeep := False;
willEnqueue := False;
FLock.Enter;
try
if FisTerminated.Read = 1 then
raise Exception.Create( 'TWorkFactory.StartTask() when terminated');
if TaskEx.Status <> tsConfigurable then exit;
willEnqueue := FWorkCapacity.Read > 0;
doHouseKeep := (FIdleCount.Read = 0) and willEnqueue;
if willEnqueue then
begin
FWorkCapacity.Decrement;
FWorkEnqueued.Increment;
TaskEx.Status := tsEnqueued
end;
finally
FLock.Leave
end;
hasEnqueued := willEnqueue and (FTaskQueue.Enqueue( TaskEx, 0) = wrSignaled);
if doHouseKeep then
FHouseKeepAlert.Signal;
result := hasEnqueued or willEnqueue;
if not result then exit;
if not hasEnqueued then