forked from gabr42/OmniThreadLibrary
-
Notifications
You must be signed in to change notification settings - Fork 1
/
OtlParallel.pas
5592 lines (5028 loc) · 206 KB
/
OtlParallel.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>High-level parallel execution management.
/// Part of the OmniThreadLibrary project. Requires Delphi 2009 or newer.</summary>
///<author>Primoz Gabrijelcic</author>
///<license>
///This software is distributed under the BSD license.
///
///Copyright (c) 2019 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 : Sean B. Durkin, HHasenack
/// Creation date : 2010-01-08
/// Last modification : 2019-01-11
/// Version : 1.53b
///</para><para>
/// History:
/// 1.53b: 2019-01-11
/// - Using Parallel.Join.OnStopInvoke failed with access violation if Join
/// was not executed with .NoWait.
/// 1.53a: 2019-01-10
/// - Fixed pool scheduling for OtlParallel threads. Since 1.52 threads were
/// incorrectly scheduled to the main pool unless IOmniTaskConfig.ThreadPool
/// was used.
/// 1.53: 2019-01-03
/// - [HHasenack] Implemented Parallel.ForEach(IEnumerator<T>) and
/// Parallel.ForEach(IEnumerable<T>). Fixes #129.
/// 1.52a: 2017-07-05
/// - IOmniParallelLoop<T>.OnStopInvoke and IOmniParallelMapper<T1, T2> is removed
/// for pre-XE7 compilers because of compiler bugs. This removes
/// Paralell.Map.OnStopInvoke and Paralell.ForEach.OnStopInvoke support for
/// pre-XE7 compilers.
/// 1.52: 2017-07-04
/// - Added IOmniTaskConfig.NoThreadPool. This allows high-level abstractions to
/// bypass thread pool entirely and run in 'non-pooled' threads.
/// 1.51: 2017-06-21
/// - Added OnStop overload that accepts 'reference to procedure (const task: IOmniTask)'
/// to Parallel.Join and Parallel.ParallelTask.
/// - Added OnStopInvoke to all abstractions that implement OnStop method.
/// - Fixed: Parallel.Future did not create task with the .Unobserved qualifier.
/// 1.50: 2017-06-11
/// - Small tweaks in TOmniTimedTask implementation.
/// 1.49b: 2017-04-06
/// - Compiles with Delphi 10.2 Tokyo.
/// - GParallelPool.IdleWorkerThreadTimeout_sec was incorrectly set to 60.000 seconds
/// instead of 60 seconds. [issue #93]
/// 1.49a: 2017-02-03
/// - If a future's cancellation token is signalled before the future is even
/// created, the future worker is not started at all. [issue #85]
/// 1.49: 2017-02-02
/// - Added property IOmniWorkItem.SkipCompletionHandler.
/// If it is set to True when work item is created or during its execution,
/// request handlers for that work item won't be called.
/// If it is set to True in the OnRequestDone_Asy handler, then only
/// OnRequestDone handler won't be called.
/// 1.48: 2017-01-31
/// - Implemented IOmniBackgroundWorker.OnStop.
/// 1.47: 2016-11-08
/// - Added function IOmniPipeline.NoThrottling which disables throttling on an
/// entire pipeline or one of its stages.
/// 1.46: 2016-10-17
/// - Implemented Parallel.TimedTask.
/// 1.45: 2016-04-21
/// - Parallel.For<T>(const arr: TArray<T>) is not available on 2009 and 2010
/// because generics support is not good enough in these two compilers.
/// 1.44: 2016-01-14
/// - Implemented EJoinException.DetachInner.
/// 1.43: 2015-12-16
/// - Implemented Parallel.For<T>(const arr: TArray<T>).
/// 1.42: 2015-12-14
/// - Added DetachException, FatalException, and IsExceptional to IOmniParallelTask.
/// 1.41: 2015-10-04
/// - Imported mobile support by [Sean].
/// 1.40: 2015-09-04
/// - TOmniPipeline.Destroy calls TOmniPipeline.Cancel so a pipeline can be shut
/// down if user forgets to call Input.CompleteAdding.
/// 1.39a: 2015-09-03
/// - IOmniPipeline.PipelineStage[].Input and .Output are now always available
/// immediately after the IOmniPipeline.Run.
/// 1.39: 2015-02-17
/// - Corrected Parallel.For execution for negative steps.
/// - Implemented Parallel.For.CancelWith.
/// 1.38: 2015-02-04
/// - NumTasks parameter can be negative. In that case, specified number of cores
/// will be reserved for other purposes and all other will be used for processing.
/// Example: If NumTasks(-2) is used when process has access to 8 cores,
/// 6 of them (8 - 2) will be used to run the task.
/// 1.37: 2015-01-30
/// - Implemented Parallel.Map.
/// - Task finalizers in Parallel.For were not called.
/// - Implemented Parallel.For.WaitFor.
/// 1.36: 2014-09-27
/// - Implemented simple and fast Parallel.&For which supports only integer ranges.
/// 1.35: 2014-07-03
/// - Added overloaded Execute methods to IOmniParallelInitializedLoop and
/// IOmniParallelInitializedLoop<T> so that IOmniTask parameter can be passed
/// to the executor.
/// 1.34a: 2014-03-13
/// - Fixed race condition in IOmniPipeline termination code.
/// 1.34: 2014-01-08
/// - Added SetPriority function to the IOmniTaskConfig.
/// 1.33: 2013-10-14
/// - Different thread pool can be specified for all operations via the new
/// TaskConfig.ThreadPool function.
/// - Included stability fixes by [Tommaso Ercole].
/// 1.32: 2013-10-13
/// - Removed optimization which caused ForEach to behave differently on
/// uniprocessor computers.
/// 1.31b: 2013-07-02
/// - Simple pipline stage handles exceptions in the executor function.
/// 1.31a: 2013-03-10
/// - ForEach destructor waits for all internal tasks to be stopped before the
/// object is destroyed.
/// 1.31: 2013-02-21
/// - Implemented IOmniPipeline.PipelineStage[] property returning Input/Ouput
/// collections of a specific stage.
/// 1.30: 2012-10-03
/// - Added Async/Await abstraction.
/// 1.29: 2012-08-12
/// - IOmniBackgroundWorker extended with task initializer (Initialize) and
/// task finalizer (Finalize).
/// - IOmniWorkItem extended with property TaskState.
/// - Inlined bunch of TOmniWorkItem methods.
/// 1.28: 2012-07-03
/// - Added OnStop overload to Parallel.Pipeline that accepts
/// 'reference to procedure (const task: IOmniTask)'.
/// 1.27: 2012-06-09
/// - Added OnStop overload to Parallel.ForEach that accepts
/// 'reference to procedure (const task: IOmniTask)'.
/// 1.26c: 2012-06-06
/// - ForEach finalizer is called if an exception occurs inside the ForEach task.
/// - Marked IOmniParallelLoop.OnMessage as deprecated.
/// 1.26b: 2012-06-05
/// - Invalid 'joinState' was passed to the worker task in Parallel.Join if number
/// of tasks to be executed was larger than the number of worker threads.
/// 1.26a: 2012-06-03
/// - Parallel.Join was broken if number of task to be executed was larger than
/// the number of worker threads.
/// 1.26: 2012-03-31
/// - Task property added to the IOmniWorkItem interface.
/// - Fixed overloaded OnMessage declaration in the IOmniTaskConfig interface.
/// 1.25: 2012-03-26
/// - Parallel.Pipeline implements OnStop.
/// 1.24b: 2012-03-21
/// - IOmniJoinState.Task was not correctly set in TOmniParallelJoin.Execute.
/// Thanks to [Mayjest] for reproducible test case.
/// 1.24a: 2012-02-23
/// - Exception handling in Async works correctly if Async has OnTerminated
/// configured.
/// 1.24: 2012-02-20
/// - Async re-raises task exception in OnTerminated handler.
/// 1.23a: 2011-12-09
/// - Removed unused global variable GPipelinePool.
/// 1.23: 2011-11-25
/// - Implemented background worker abstraction, Parallel.BackgroundWorker.
/// 1.22a: 2011-11-16
/// - Number of producers/consumers in TOmniForkJoin<T>.StartWorkerTasks was off
/// by 1. Thanks to [meishier] for tracking the bug down.
/// 1.22: 2011-11-15
/// - Parallel.Join implementation fixed to not depend on thread pool specifics.
/// Parallel.Join.NumTasks works again.
/// - GUIDs removed again (GUIDs on generic interfaces don't work). Hard casting is
/// used whenever possible.
/// 1.21: 2011-11-11
/// - All interfaces decorated with GUIDs.
/// 1.20a: 2011-11-09
/// - [Anton Alisov] Fixed potential leak in Pipeline exception handling.
/// 1.20: 2011-11-03
/// - Fixed two Parallel.Pipeline overloads to not override internal input
/// collection if 'input' parameter was not provided.
/// - Only one thread pool used internally.
/// - GlobalParallelPool no longer limits maximum number of concurrent threads.
/// 1.19: 2011-11-01
/// - Implemented IOmniParallelTask.TaskConfig.
/// - Added IOmniParallelTask.Execute overload.
/// - Added IOmniParallelIntoLoop and IOmniParallelIntoLoop<T> Execute overload.
/// 1.18: 2011-09-06
/// - Initial implementation of the Parallel.ParallelTask.
/// - Parallel.Join implements OnStop.
/// 1.17: 2011-08-29
/// - *** Breaking change *** IOmniPipeline.Input renamed to IOmniPipeline.From.
/// - *** Breaking change *** IOmniPipeline.Run now returns Self instead of
/// IOmniBlockingCollection.
/// - Added properties Input, Output: IOmniBlockingCollection to the IOmniPipeline.
/// Input always points to valid blocking collection (either the built-in one or
/// to the collection provided in the From method) and can be used to send data
/// to the first stage. Output can be used to read data from the last stage.
/// - Exception in any stage is caught and stored as an exception object in the
/// TOmniValue wrapper, which is passed to the output collection so it can be
/// processed by the next stage. By default, the next stage automatically reraises
/// this exception (and so on until the exception is passed to the final
/// collection) until you decorate the stage with the .HandleExceptions method.
/// (You can also mark all stages to handle exceptions by calling HandleExceptions
/// before defining any stage.) If a stage is handling exceptions, it will receive
/// TOmniValue holding an exception on input (value.IsException will be true). In
/// this case, it should either reraise the exception or (eventually) release the
/// exception object (value.AsException.Free). Demo 48_OtlParallelExceptions shows
/// possible ways to handle exceptions in the IOmniPipeline.
/// 1.16: 2011-08-27
/// - Added two more Parallel.Pipeline overloads.
/// - Parallel.Pipeline accepts simple stages - TPipelineSimpleStageDelegate -
/// where collection iteration is implemented internally.
/// - Implemented IOmniPipeline.WaitFor.
/// - Added support for parameterless OnTerminated version to the TaskConfig.
/// 1.15: 2011-07-26
/// - *** Breaking change *** Parallel.Join reimplemented as IOmniParallelJoin
/// interface to add exception and cancellation support. User code must call
/// .Execute on the interface returned from the Parallel.Join to start the
/// execution.
/// - Parallel.Join(const task: TOmniTaskDelegate) is no longer supported. It was
/// replaced with the Parallel.Join(const task: IOmniJoinState).
/// - Parallel.Join no longer supports taskConfig parameter (replaced by the
/// IOmniParallelJoin.TaskConfig function).
/// - Number of simultaneously executed task in Parallel.Join may be set by calling
/// the new IOmniParallelJoin.NumTasks function.
/// 1.14: 2011-07-21
/// - Parallel.Future implements WaitFor.
/// 1.13: 2011-07-18
/// - Added exception handling to Parallel.Join. Tasks' fatal exceptions are wrapped
/// in EJoinException and raised at the end of Parallel.Join method.
/// - Two version of Parallel.Async (the ones with explicit termination handlers)
/// were removed as this functionality can be achieved by using
/// Parallel.TaskConfig.OnTerminated.
/// 1.12: 2011-07-18
/// - Added exception handling to IOmniFuture<T>. Tasks' fatal exception is raised
/// in .Value. New function .FatalException and .DetachException.
/// - Parallel.Join with TProc parameters was leaking memory.
/// 1.11: 2011-07-16
/// - GParallelPool and GPipelinePool are now initialized on the fly which allows
/// OtlParallel to be used inside a DLL.
/// - GParallelPool and GPipelinePool are now private and must be accessed with
/// global methods GlobalParallelPool and GlobalPipelinePool.
/// 1.10a: 2011-06-25
/// - Bug fixed: Parallel.ForEach was never running on more than
/// Process.Affinity.Count tasks.
/// 1.10: 2011-04-16
/// - Parallel.Join supports TaskConfig.
/// - Parallel.Future supports TaskConfig.
/// - Parallel.Pipeline supports TaskConfig.
/// - Parallel.ForEach supports TaskConfig.
/// 1.09: 2011-04-06
/// - Implemented Parallel.ForkJoin.
/// - Implemented Parallel.Async.
/// - Implemented Parallel.TaskConfig.
/// 1.08: 2011-03-09
/// - Faster IOmniFuture<T>.IsDone.
/// 1.07a: 2011-02-15
/// - Compiles in Delphi 2009.
/// 1.07: 2010-12-09
/// - Parallel.Join(TProc) executes one task in the current thread.
/// - Parallel.ForEach.NoWait runs on NumCores-1 tasks.
/// - Parallel.Pipeline throttling low watermark defaults to 1/4 of the high
/// watermark if pipeline runs on more tasks than there are available cores.
/// 1.06: 2010-12-02
/// - Parallel.Pipeline implements Cancel method.
/// - Parallel.Pipeline stage delegate can accept additional parameter of type
/// IOmniTask. Stage can use it to check if the pipeline was cancelled.
/// - Implemented task state in ForEach (ForEach.Initialize.Finalize.Execute).
/// 1.05c: 2010-11-25
/// - CompleteAdding is called only when all tasks for the stage have completed the
/// work.
/// - .NumTasks works correctly after .Stage().
/// 1.05b: 2010-11-25
/// - Parallel.Pipeline uses its own thread pool with unlimited number of running
/// threads.
/// 1.05a: 2010-11-22
/// - Two overloaded versions of Join added back. They were needed after all.
/// - Fixed bugs in Join implementation - thanks to Mason Wheeler for
/// the bug report.
/// - Parallel.Pipeline.Run returns output collection.
/// - Parallel.Pipeline.Throttle is fully implemented. Throttling level defaults to
/// 10240 elements.
/// 1.05: 2010-11-21
/// - OtlFutures functionality moved into this unit.
/// - Futures can be created by calling Parallel.Future<T>(action).
/// - GForEachPool renamed into GParallelPool and used for all Parallel
/// tasking.
/// - Two overloaded versions of Join removed.
/// 1.04: 2010-11-20
/// - Small fix regarding setting GParallelPool.MaxExecuting.
/// 1.04: 2010-07-22
/// - Introduced overloaded Execute methods with delegates that accept the task
/// interface parameter.
/// - Introduced OnTaskCreate hook and MonitorWith shorthand.
/// 1.03: 2010-07-17
/// - ForEach tasks are scheduled in the specialized pool.
/// 1.02: 2010-07-01
/// - Includes OTLOptions.inc.
/// 1.01: 2010-02-02
/// - Implemented ForEach(rangeLow, rangeHigh).
/// - Implemented ForEach.Aggregate.
/// - ForEach optimized for execution on single-core computer.
/// - Implemented Parallel.Join.
/// - Removed Stop method. Loop can be cancelled with a cancellation token.
/// 1.0: 2010-01-14
/// - Released.
///</para></remarks>
// http://msdn.microsoft.com/en-us/magazine/cc163340.aspx
// http://blogs.msdn.com/pfxteam/archive/2007/11/29/6558543.aspx
// http://cis.jhu.edu/~dsimcha/parallelFuture.html
unit OtlParallel;
{$I OtlOptions.inc}
interface
// TODO 1 -oPrimoz Gabrijelcic : Replace OnStop with TaskConfig.OnTerminate whenever appropriate?
// TODO 1 -oPrimoz Gabrijelcic : IOmniParallelLoop.Initialize should return 'normal' interface which should implement Finalize; no need for 'InitializedLoop' interface
// TODO 1 -oPrimoz Gabrijelcic : IOmniParallelLoop.Execute should return 'self'
// TODO 1 -oPrimoz Gabrijelcic : Remove IOmniParallelLoop.OnMessage
// TODO 1 -oPrimoz Gabrijelcic : IOmniFuture<T>.IsExceptional
// TODO 1 -oPrimoz Gabrijelcic : ??TryFatalException with timeout??
// TODO 3 -oPrimoz Gabrijelcic : Maybe we could use .Aggregate<T> where T is the aggregate type?
// TODO 3 -oPrimoz Gabrijelcic : Change .Aggregate to use .Into signature for loop body?
// TODO 1 -oPrimoz Gabrijelcic : How to combine Futures and NoWait version of Aggregate?
// TODO 5 -oPrimoz Gabrijelcic : Single-threaded access to a data source - how? (datasets etc)
// TODO 3 -oPrimoz Gabrijelcic : Parallel.MapReduce?
// Notes for OTL 3
// - Parallel.ForEach should use task pool.
// - Task pool would dynamically schedule tasks over available cores.
// - Task pool would know how many different kinds of tasks are there (one per distinct
// ForEach) and would balance load so that all different kinds of tasks would get executed.
// - ForEach would support .DegreeOfConcurrency (or something like that) which would
// default to one meaning that one task can easily consume one core. Setting it to two
// (it would be a real, not integer) would mean that one task can only consume one half of a
// core and that 2*<number of cores> is a good number of threads for this particular task.
uses
{$IFDEF MSWINDOWS}
Windows,
Messages,
{$ENDIF MSWINDOWS}
SysUtils,
{$IFDEF OTL_ERTTI}
TypInfo,
RTTI,
{$ENDIF OTL_ERTTI}
SyncObjs,
Generics.Collections,
GpLists,
OtlCommon,
OtlSync,
OtlCollections,
OtlTask,
OtlTaskControl,
OtlDataManager,
OtlEventMonitor,
OtlThreadPool;
const
CDefaultPipelineThrottle = 10240;
type
IOmniTaskConfig = interface
procedure Apply(const task: IOmniTaskControl);
function CancelWith(const token: IOmniCancellationToken): IOmniTaskConfig;
function MonitorWith(const monitor: IOmniTaskControlMonitor): IOmniTaskConfig;
function NoThreadPool: IOmniTaskConfig;
function OnMessage(eventDispatcher: TObject): IOmniTaskConfig; overload;
function OnMessage(eventHandler: TOmniTaskMessageEvent): IOmniTaskConfig; overload;
function OnMessage(msgID: word; eventHandler: TOmniTaskMessageEvent): IOmniTaskConfig; overload;
function OnMessage(msgID: word; eventHandler: TOmniOnMessageFunction): IOmniTaskConfig; overload;
function OnTerminated(eventHandler: TOmniTaskTerminatedEvent): IOmniTaskConfig; overload;
function OnTerminated(eventHandler: TOmniOnTerminatedFunction): IOmniTaskConfig; overload;
function OnTerminated(eventHandler: TOmniOnTerminatedFunctionSimple): IOmniTaskConfig; overload;
function SetPriority(threadPriority: TOTLThreadPriority): IOmniTaskConfig;
function ThreadPool(const threadPool: IOmniThreadPool): IOmniTaskConfig;
function WithCounter(const counter: IOmniCounter): IOmniTaskConfig;
function WithLock(const lock: TSynchroObject; autoDestroyLock: boolean = true): IOmniTaskConfig; overload;
function WithLock(const lock: IOmniCriticalSection): IOmniTaskConfig; overload;
// property Param: TOmniValueContainer read GetParam;
end; { IOmniTaskConfig }
IOmniParallelLoop = interface;
IOmniParallelLoop<T> = interface;
TOmniAggregatorDelegate = reference to procedure(var aggregate: TOmniValue; const value: TOmniValue);
TOmniIteratorDelegate = reference to procedure(const value: TOmniValue);
TOmniIteratorDelegate<T> = reference to procedure(const value: T);
TOmniIteratorTaskDelegate = reference to procedure(const task: IOmniTask; const value: TOmniValue);
TOmniIteratorTaskDelegate<T> = reference to procedure(const task: IOmniTask; const value: T);
TOmniIteratorStateDelegate = reference to procedure(const value: TOmniValue; var taskState: TOmniValue);
TOmniIteratorStateDelegate<T> = reference to procedure(const value: T; var taskState: TOmniValue);
TOmniIteratorStateTaskDelegate = reference to procedure(const task: IOmniTask; const value: TOmniValue; var taskState: TOmniValue);
TOmniIteratorStateTaskDelegate<T> = reference to procedure(const task: IOmniTask; const value: T; var taskState: TOmniValue);
TOmniIteratorIntoDelegate = reference to procedure(const value: TOmniValue; var result: TOmniValue);
TOmniIteratorIntoDelegate<T> = reference to procedure(const value: T; var result: TOmniValue);
TOmniIteratorIntoTaskDelegate = reference to procedure(const task: IOmniTask; const value: TOmniValue; var result: TOmniValue);
TOmniIteratorIntoTaskDelegate<T> = reference to procedure(const task: IOmniTask; const value: T; var result: TOmniValue);
TOmniTaskCreateDelegate = TOmniTaskDelegate;
TOmniTaskControlCreateDelegate = reference to procedure(const task: IOmniTaskControl);
TOmniTaskInitializerDelegate = reference to procedure(var taskState: TOmniValue);
TOmniTaskFinalizerDelegate = reference to procedure(const taskState: TOmniValue);
IOmniParallelAggregatorLoop = interface
function Execute(loopBody: TOmniIteratorIntoDelegate): TOmniValue;
end; { IOmniParallelAggregatorLoop }
IOmniParallelAggregatorLoop<T> = interface
function Execute(loopBody: TOmniIteratorIntoDelegate<T>): TOmniValue;
end; { IOmniParallelAggregatorLoop<T> }
IOmniParallelInitializedLoop = interface
function Finalize(taskFinalizer: TOmniTaskFinalizerDelegate): IOmniParallelInitializedLoop;
procedure Execute(loopBody: TOmniIteratorStateDelegate); overload;
procedure Execute(loopBody: TOmniIteratorStateTaskDelegate); overload;
end; { IOmniParallelInitializedLoop }
IOmniParallelInitializedLoop<T> = interface
function Finalize(taskFinalizer: TOmniTaskFinalizerDelegate): IOmniParallelInitializedLoop<T>;
procedure Execute(loopBody: TOmniIteratorStateDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorStateTaskDelegate<T>); overload;
end; { IOmniParallelInitializedLoop }
IOmniParallelIntoLoop = interface
procedure Execute(loopBody: TOmniIteratorIntoDelegate); overload;
procedure Execute(loopBody: TOmniIteratorIntoTaskDelegate); overload;
end; { IOmniParallelIntoLoop }
IOmniParallelIntoLoop<T> = interface
procedure Execute(loopBody: TOmniIteratorIntoDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorIntoTaskDelegate<T>); overload;
end; { IOmniParallelIntoLoop<T> }
TOmniTaskStopDelegate = TOmniTaskDelegate;
IOmniParallelLoop = interface
function Aggregate(defaultAggregateValue: TOmniValue;
aggregator: TOmniAggregatorDelegate): IOmniParallelAggregatorLoop;
function AggregateSum: IOmniParallelAggregatorLoop;
function CancelWith(const token: IOmniCancellationToken): IOmniParallelLoop;
procedure Execute(loopBody: TOmniIteratorDelegate); overload;
procedure Execute(loopBody: TOmniIteratorTaskDelegate); overload;
function Initialize(taskInitializer: TOmniTaskInitializerDelegate): IOmniParallelInitializedLoop;
function Into(const queue: IOmniBlockingCollection): IOmniParallelIntoLoop; overload;
function NoWait: IOmniParallelLoop;
function NumTasks(taskCount : integer): IOmniParallelLoop;
function OnMessage(eventDispatcher: TObject): IOmniParallelLoop; overload; deprecated 'use TaskConfig';
function OnMessage(msgID: word; eventHandler: TOmniTaskMessageEvent): IOmniParallelLoop; overload; deprecated 'use TaskConfig';
function OnMessage(msgID: word; eventHandler: TOmniOnMessageFunction): IOmniParallelLoop; overload; deprecated 'use TaskConfig';
function OnTaskCreate(taskCreateDelegate: TOmniTaskCreateDelegate): IOmniParallelLoop; overload;
function OnTaskCreate(taskCreateDelegate: TOmniTaskControlCreateDelegate): IOmniParallelLoop; overload;
function OnStop(stopCode: TProc): IOmniParallelLoop; overload;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniParallelLoop; overload;
function OnStopInvoke(stopCode: TProc): IOmniParallelLoop;
function PreserveOrder: IOmniParallelLoop;
function TaskConfig(const config: IOmniTaskConfig): IOmniParallelLoop;
end; { IOmniParallelLoop }
IOmniParallelLoop<T> = interface
function Aggregate(defaultAggregateValue: TOmniValue;
aggregator: TOmniAggregatorDelegate): IOmniParallelAggregatorLoop<T>;
function AggregateSum: IOmniParallelAggregatorLoop<T>;
procedure Execute(loopBody: TOmniIteratorDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorTaskDelegate<T>); overload;
function CancelWith(const token: IOmniCancellationToken): IOmniParallelLoop<T>;
function Initialize(taskInitializer: TOmniTaskInitializerDelegate): IOmniParallelInitializedLoop<T>;
function Into(const queue: IOmniBlockingCollection): IOmniParallelIntoLoop<T>; overload;
function NoWait: IOmniParallelLoop<T>;
function NumTasks(taskCount: integer): IOmniParallelLoop<T>;
function OnMessage(eventDispatcher: TObject): IOmniParallelLoop<T>; overload; deprecated 'use TaskConfig';
function OnMessage(msgID: word; eventHandler: TOmniTaskMessageEvent): IOmniParallelLoop<T>; overload; deprecated 'use TaskConfig';
function OnMessage(msgID: word; eventHandler: TOmniOnMessageFunction): IOmniParallelLoop<T>; overload; deprecated 'use TaskConfig';
function OnTaskCreate(taskCreateDelegate: TOmniTaskCreateDelegate): IOmniParallelLoop<T>; overload;
function OnTaskCreate(taskCreateDelegate: TOmniTaskControlCreateDelegate): IOmniParallelLoop<T>; overload;
function OnStop(stopCode: TProc): IOmniParallelLoop<T>; overload;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniParallelLoop<T>; overload;
{$IFDEF OTL_FixedGenericIncompletelyDefined}
function OnStopInvoke(stopCode: TProc): IOmniParallelLoop<T>;
{$ENDIF OTL_FixedGenericIncompletelyDefined}
function PreserveOrder: IOmniParallelLoop<T>;
function TaskConfig(const config: IOmniTaskConfig): IOmniParallelLoop<T>;
end; { IOmniParallelLoop<T> }
TOmniIteratorSimpleSimpleDelegate = reference to procedure(value: integer);
TOmniIteratorSimpleDelegate = reference to procedure(taskIndex, value: integer);
TOmniIteratorSimpleFullDelegate = reference to procedure(const task: IOmniTask; taskIndex, value: integer);
TOmniSimpleTaskInitializerDelegate = reference to procedure(taskIndex, fromIndex, toIndex: integer);
TOmniSimpleTaskInitializerTaskDelegate = reference to procedure(const task: IOmniTask; taskIndex, fromIndex, toIndex: integer);
TOmniSimpleTaskFinalizerDelegate = reference to procedure(taskIndex, fromIndex, toIndex: integer);
TOmniSimpleTaskFinalizerTaskDelegate = reference to procedure(const task: IOmniTask; taskIndex, fromIndex, toIndex: integer);
IOmniParallelSimpleLoop = interface
function CancelWith(const token: IOmniCancellationToken): IOmniParallelSimpleLoop;
function NoWait: IOmniParallelSimpleLoop;
function NumTasks(taskCount : integer): IOmniParallelSimpleLoop;
function OnStop(stopCode: TProc): IOmniParallelSimpleLoop; overload;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniParallelSimpleLoop; overload;
function OnStopInvoke(stopCode: TProc): IOmniParallelSimpleLoop;
function TaskConfig(const config: IOmniTaskConfig): IOmniParallelSimpleLoop;
procedure Execute(loopBody: TOmniIteratorSimpleSimpleDelegate); overload;
procedure Execute(loopBody: TOmniIteratorSimpleDelegate); overload;
procedure Execute(loopBody: TOmniIteratorSimpleFullDelegate); overload;
function Initialize(taskInitializer: TOmniSimpleTaskInitializerDelegate): IOmniParallelSimpleLoop; overload;
function Initialize(taskInitializer: TOmniSimpleTaskInitializerTaskDelegate): IOmniParallelSimpleLoop; overload;
function Finalize(taskFinalizer: TOmniSimpleTaskFinalizerDelegate): IOmniParallelSimpleLoop; overload;
function Finalize(taskFinalizer: TOmniSimpleTaskFinalizerTaskDelegate): IOmniParallelSimpleLoop; overload;
function WaitFor(maxWait_ms: cardinal): boolean;
end; { IOmniParallelSimpleLoop }
{$IFDEF OTL_GoodGenerics}
TOmniIteratorSimpleSimpleDelegate<T> = reference to procedure(var value: T);
TOmniIteratorSimpleDelegate<T> = reference to procedure(taskIndex: integer; var value: T);
TOmniIteratorSimpleFullDelegate<T> = reference to procedure(const task: IOmniTask; taskIndex: integer; var value: T);
IOmniParallelSimpleLoop<T> = interface
function CancelWith(const token: IOmniCancellationToken): IOmniParallelSimpleLoop<T>;
function NoWait: IOmniParallelSimpleLoop<T>;
function NumTasks(taskCount : integer): IOmniParallelSimpleLoop<T>;
function OnStop(stopCode: TProc): IOmniParallelSimpleLoop<T>; overload;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniParallelSimpleLoop<T>; overload;
function OnStopInvoke(stopCode: TProc): IOmniParallelSimpleLoop<T>;
function TaskConfig(const config: IOmniTaskConfig): IOmniParallelSimpleLoop<T>;
procedure Execute(loopBody: TOmniIteratorSimpleSimpleDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorSimpleDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorSimpleFullDelegate<T>); overload;
function Initialize(taskInitializer: TOmniSimpleTaskInitializerDelegate): IOmniParallelSimpleLoop<T>; overload;
function Initialize(taskInitializer: TOmniSimpleTaskInitializerTaskDelegate): IOmniParallelSimpleLoop<T>; overload;
function Finalize(taskFinalizer: TOmniSimpleTaskFinalizerDelegate): IOmniParallelSimpleLoop<T>; overload;
function Finalize(taskFinalizer: TOmniSimpleTaskFinalizerTaskDelegate): IOmniParallelSimpleLoop<T>; overload;
function WaitFor(maxWait_ms: cardinal): boolean;
end; { IOmniParallelSimpleLoop }
{$ENDIF OTL_GoodGenerics}
TEnumeratorDelegate = reference to function(var next: TOmniValue): boolean;
TEnumeratorDelegate<T> = reference to function(var next: T): boolean;
TOmniFutureDelegate<T> = reference to function: T;
TOmniFutureDelegateEx<T> = reference to function(const task: IOmniTask): T;
IOmniFuture<T> = interface
procedure Cancel;
function DetachException: Exception;
function FatalException: Exception;
function IsCancelled: boolean;
function IsDone: boolean;
function TryValue(timeout_ms: cardinal; var value: T): boolean;
function Value: T;
function WaitFor(timeout_ms: cardinal): boolean;
end; { IOmniFuture<T> }
TOmniFuture<T> = class(TInterfacedObject, IOmniFuture<T>)
strict private
FCancellable : boolean;
FCancelled : boolean;
FCompleted : boolean;
FTaskException: Exception;
FResult : T;
FTask : IOmniTaskControl;
strict protected
procedure DestroyTask;
procedure DetachExceptionFromTask;
procedure Execute(action: TOmniTaskDelegate; taskConfig: IOmniTaskConfig);
public
constructor Create(action: TOmniFutureDelegate<T>; taskConfig: IOmniTaskConfig = nil); // sadly, those two Creates cannot be overloaded as this crashes the compiler (internal error T888)
constructor CreateEx(action: TOmniFutureDelegateEx<T>; taskConfig: IOmniTaskConfig = nil);
destructor Destroy; override;
procedure Cancel;
function DetachException: Exception; inline;
function FatalException: Exception; inline;
function IsCancelled: boolean; inline;
function IsDone: boolean;
function TryValue(timeout_ms: cardinal; var value: T): boolean;
function Value: T;
function WaitFor(timeout_ms: cardinal): boolean;
end; { TOmniFuture<T> }
EFutureError = class(Exception);
EFutureCancelled = class(Exception);
IOmniPipelineStage = interface ['{DFDA7A07-6B28-4AA6-9218-59D3DF9C4B8E}']
function GetInput: IOmniBlockingCollection;
function GetOutput: IOmniBlockingCollection;
//
property Input: IOmniBlockingCollection read GetInput;
property Output: IOmniBlockingCollection read GetOutput;
end; { IOmniPipelineStage }
TPipelineSimpleStageDelegate = reference to procedure (const input: TOmniValue;
var output: TOmniValue);
TPipelineStageDelegate = reference to procedure (const input, output:
IOmniBlockingCollection);
TPipelineStageDelegateEx = reference to procedure (const input, output:
IOmniBlockingCollection; const task: IOmniTask);
IOmniPipeline = interface
function GetInput: IOmniBlockingCollection;
function GetOutput: IOmniBlockingCollection;
function GetPipelineStage(idxStage: integer): IOmniPipelineStage;
//
procedure Cancel;
function From(const queue: IOmniBlockingCollection): IOmniPipeline;
function HandleExceptions: IOmniPipeline;
function NumTasks(numTasks: integer): IOmniPipeline;
function OnStop(stopCode: TProc): IOmniPipeline; overload;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniPipeline; overload;
function OnStopInvoke(stopCode: TProc): IOmniPipeline;
function NoThrottling: IOmniPipeline;
function Run: IOmniPipeline;
function Stage(pipelineStage: TPipelineSimpleStageDelegate; taskConfig: IOmniTaskConfig = nil): IOmniPipeline; overload;
function Stage(pipelineStage: TPipelineStageDelegate; taskConfig: IOmniTaskConfig = nil): IOmniPipeline; overload;
function Stage(pipelineStage: TPipelineStageDelegateEx; taskConfig: IOmniTaskConfig = nil): IOmniPipeline; overload;
function Stages(const pipelineStages: array of TPipelineSimpleStageDelegate; taskConfig: IOmniTaskConfig = nil): IOmniPipeline; overload;
function Stages(const pipelineStages: array of TPipelineStageDelegate; taskConfig: IOmniTaskConfig = nil): IOmniPipeline; overload;
function Stages(const pipelineStages: array of TPipelineStageDelegateEx; taskConfig: IOmniTaskConfig = nil): IOmniPipeline; overload;
function Throttle(numEntries: integer; unblockAtCount: integer = 0): IOmniPipeline;
function WaitFor(timeout_ms: cardinal): boolean;
property Input: IOmniBlockingCollection read GetInput;
property Output: IOmniBlockingCollection read GetOutput;
property PipelineStage[idxStage: integer]: IOmniPipelineStage read GetPipelineStage;
end; { IOmniPipeline }
TOmniForkJoinDelegate = reference to procedure;
TOmniForkJoinDelegateEx = TOmniTaskDelegate;
TOmniForkJoinDelegate<T> = reference to function: T;
TOmniForkJoinDelegateEx<T> = reference to function(const task: IOmniTask): T;
IOmniCompute = interface
procedure Execute;
function IsDone: boolean;
procedure Await;
end; { IOmniCompute<T> }
IOmniCompute<T> = interface
procedure Execute;
function IsDone: boolean;
function TryValue(timeout_ms: cardinal; var value: T): boolean;
function Value: T;
end; { IOmniCompute<T> }
TOmniCompute<T> = class(TInterfacedObject, IOmniCompute<T>)
strict private
FAction : TOmniForkJoinDelegate<T>;
FComputed: boolean;
FInput : IOmniBlockingCollection;
FResult : T;
public
constructor Create(action: TOmniForkJoinDelegate<T>; input: IOmniBlockingCollection);
procedure Execute;
function IsDone: boolean;
function TryValue(timeout_ms: cardinal; var value: T): boolean;
function Value: T;
end; { TOmniCompute<T> }
TOmniCompute = class(TInterfacedObject, IOmniCompute)
strict private
FCompute: IOmniCompute<boolean>;
public
constructor Create(compute: IOmniCompute<boolean>);
procedure Await;
procedure Execute;
function IsDone: boolean;
end; { TOmniCompute }
IOmniForkJoin = interface
function Compute(action: TOmniForkJoinDelegate): IOmniCompute;
function NumTasks(numTasks: integer): IOmniForkJoin;
function TaskConfig(const config: IOmniTaskConfig): IOmniForkJoin;
end; { IOmniForkJoin }
IOmniForkJoin<T> = interface
function Compute(action: TOmniForkJoinDelegate<T>): IOmniCompute<T>;
function NumTasks(numTasks: integer): IOmniForkJoin<T>;
function TaskConfig(const config: IOmniTaskConfig): IOmniForkJoin<T>;
end; { IOmniForkJoin<T> }
TOmniForkJoin<T> = class(TInterfacedObject, IOmniForkJoin<T>)
strict private
FNumTasks : integer;
FPoolInput : IOmniBlockingCollection;
FTaskConfig: IOmniTaskConfig;
FTaskPool : IOmniPipeline;
strict protected
procedure Asy_ProcessComputations(const input, output: IOmniBlockingCollection);
procedure StartWorkerTasks;
public
constructor Create;
function Compute(action: TOmniForkJoinDelegate<T>): IOmniCompute<T>;
function NumTasks(numTasks: integer): IOmniForkJoin<T>;
function TaskConfig(const config: IOmniTaskConfig): IOmniForkJoin<T>;
end; { TOmniForkJoin }
TOmniForkJoin = class(TInterfacedObject, IOmniForkJoin)
strict private
FForkJoin: TOmniForkJoin<boolean>;
public
constructor Create;
destructor Destroy; override;
function Compute(action: TOmniForkJoinDelegate): IOmniCompute;
function NumTasks(numTasks: integer): IOmniForkJoin;
function TaskConfig(const config: IOmniTaskConfig): IOmniForkJoin;
end; { TOmniForkJoin }
TOmniDelegateEnumerator = class(TOmniValueEnumerator)
strict private
FDelegate: TEnumeratorDelegate;
FValue : TOmniValue;
public
constructor Create(delegate: TEnumeratorDelegate);
function GetCurrent: TOmniValue; override;
function MoveNext: boolean; override;
end; { TOmniDelegateEnumerator }
TOmniDelegateEnumerator<T> = class(TOmniValueEnumerator)
strict private
FDelegate: TEnumeratorDelegate<T>;
FValue : T;
public
constructor Create(delegate: TEnumeratorDelegate<T>);
function GetCurrent: TOmniValue; override;
function MoveNext: boolean; override;
end; { TOmniDelegateEnumerator }
TOmniParallelLoopOption = (ploNoWait, ploPreserveOrder);
TOmniParallelLoopOptions = set of TOmniParallelLoopOption;
TOmniParallelLoopBase = class(TInterfacedObject)
{$IFDEF OTL_ERTTI}
strict private
FDestroy : TRttiMethod;
FEnumerable : TValue;
FGetCurrent : TRttiMethod;
FMoveNext : TRttiMethod;
FRttiContext: TRttiContext;
public
constructor Create(enumerable: TObject); overload;
{$ENDIF OTL_ERTTI}
strict private
FAggregate : TOmniValue;
FAggregator : TOmniAggregatorDelegate;
FCancellationToken : IOmniCancellationToken;
FCountStopped : IOmniResourceCount;
FDataManager : TOmniDataManager;
FDelegateEnum : TOmniDelegateEnumerator;
FIntoQueueIntf : IOmniBlockingCollection;
FManagedProvider : boolean;
FNumTasks : integer;
FNumTasksManual : boolean;
FOnMessageList : TGpIntegerObjectList;
FOnStop : TOmniTaskStopDelegate;
FOnTaskControlCreate: TOmniTaskControlCreateDelegate;
FOnTaskCreate : TOmniTaskCreateDelegate;
FOptions : TOmniParallelLoopOptions;
FSourceProvider : TOmniSourceProvider;
FTaskConfig : IOmniTaskConfig;
FTaskFinalizer : TOmniTaskFinalizerDelegate;
FTaskInitializer : TOmniTaskInitializerDelegate;
strict protected
procedure DoOnStop(const task: IOmniTask);
procedure InternalExecute(loopBody: TOmniIteratorDelegate); overload;
procedure InternalExecute(loopBody: TOmniIteratorTaskDelegate); overload;
procedure InternalExecute(loopBody: TOmniIteratorStateDelegate); overload;
procedure InternalExecute(loopBody: TOmniIteratorStateTaskDelegate); overload;
function InternalExecuteAggregate(loopBody: TOmniIteratorIntoDelegate): TOmniValue; overload;
function InternalExecuteAggregate(loopBody: TOmniIteratorIntoTaskDelegate): TOmniValue; overload;
procedure InternalExecuteInto(loopBody: TOmniIteratorIntoDelegate); overload;
procedure InternalExecuteInto(loopBody: TOmniIteratorIntoTaskDelegate); overload;
procedure InternalExecuteIntoOrdered(loopBody: TOmniIteratorIntoDelegate); overload;
procedure InternalExecuteIntoOrdered(loopBody: TOmniIteratorIntoTaskDelegate); overload;
procedure InternalExecuteTask(taskDelegate: TOmniTaskDelegate);
procedure SetAggregator(defaultAggregateValue: TOmniValue;
aggregator: TOmniAggregatorDelegate);
procedure SetAggregatorSum;
procedure SetCancellationToken(const token: IOmniCancellationToken);
procedure SetFinalizer(taskFinalizer: TOmniTaskFinalizerDelegate);
procedure SetInitializer(taskInitializer: TOmniTaskInitializerDelegate);
procedure SetIntoQueue(const queue: IOmniBlockingCollection); overload;
procedure SetNumTasks(taskCount: integer);
procedure SetOnMessage(eventDispatcher: TObject); overload;
procedure SetOnMessage(msgID: word; eventHandler: TOmniTaskMessageEvent); overload;
procedure SetOnMessage(msgID: word; eventHandler: TOmniOnMessageFunction); overload;
procedure SetOnTaskCreate(taskCreateDelegate: TOmniTaskCreateDelegate); overload;
procedure SetOnTaskCreate(taskCreateDelegate: TOmniTaskControlCreateDelegate); overload;
procedure SetOnStop(stopDelegate: TOmniTaskStopDelegate);
procedure SetTaskConfig(const config: IOmniTaskConfig);
function Stopped: boolean; inline;
public
constructor Create(const sourceProvider: TOmniSourceProvider; managedProvider: boolean); overload;
constructor Create(const enumerator: TEnumeratorDelegate); overload;
destructor Destroy; override;
property Options: TOmniParallelLoopOptions read FOptions write FOptions;
end; { TOmniParallelLoopBase }
TOmniParallelLoop = class(TOmniParallelLoopBase, IOmniParallelLoop,
IOmniParallelAggregatorLoop,
IOmniParallelInitializedLoop,
IOmniParallelIntoLoop)
public
function Aggregate(defaultAggregateValue: TOmniValue;
aggregator: TOmniAggregatorDelegate): IOmniParallelAggregatorLoop;
function AggregateSum: IOmniParallelAggregatorLoop;
function CancelWith(const token: IOmniCancellationToken): IOmniParallelLoop;
function ExecuteAggregate(loopBody: TOmniIteratorIntoDelegate): TOmniValue; overload;
function ExecuteAggregate(loopBody: TOmniIteratorIntoTaskDelegate): TOmniValue; overload;
function IOmniParallelAggregatorLoop.Execute = ExecuteAggregate;
procedure Execute(loopBody: TOmniIteratorDelegate); overload;
procedure Execute(loopBody: TOmniIteratorTaskDelegate); overload;
procedure Execute(loopBody: TOmniIteratorIntoDelegate); overload;
procedure Execute(loopBody: TOmniIteratorIntoTaskDelegate); overload;
procedure Execute(loopBody: TOmniIteratorStateDelegate); overload;
procedure Execute(loopBody: TOmniIteratorStateTaskDelegate); overload;
function Finalize(taskFinalizer: TOmniTaskFinalizerDelegate):
IOmniParallelInitializedLoop;
function Initialize(taskInitializer: TOmniTaskInitializerDelegate):
IOmniParallelInitializedLoop;
function Into(const queue: IOmniBlockingCollection): IOmniParallelIntoLoop; overload;
function NoWait: IOmniParallelLoop;
function NumTasks(taskCount: integer): IOmniParallelLoop;
function OnMessage(eventDispatcher: TObject): IOmniParallelLoop; overload;
function OnMessage(msgID: word; eventHandler: TOmniTaskMessageEvent): IOmniParallelLoop; overload;
function OnMessage(msgID: word; eventHandler: TOmniOnMessageFunction): IOmniParallelLoop; overload;
function OnTaskCreate(taskCreateDelegate: TOmniTaskCreateDelegate): IOmniParallelLoop; overload;
function OnTaskCreate(taskCreateDelegate: TOmniTaskControlCreateDelegate): IOmniParallelLoop; overload;
function OnStop(stopCode: TProc): IOmniParallelLoop; overload;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniParallelLoop; overload;
function OnStopInvoke(stopCode: TProc): IOmniParallelLoop;
function PreserveOrder: IOmniParallelLoop;
function TaskConfig(const config: IOmniTaskConfig): IOmniParallelLoop;
end; { TOmniParallelLoop }
TOmniParallelLoop<T> = class(TOmniParallelLoopBase, IOmniParallelLoop<T>,
IOmniParallelAggregatorLoop<T>,
IOmniParallelInitializedLoop<T>,
IOmniParallelIntoLoop<T>)
strict private type
TItoTEnumeratorWrapper = class(TEnumerator<T>)
private
FEnumerator: IEnumerator<T>;
protected
function DoMoveNext: boolean; override;
function DoGetCurrent: T; override;
public
constructor Create(const AEnum: IEnumerator<T>);
end; { TItoTEnumeratorWrapper<T> }
var
FDelegateEnum: TOmniDelegateEnumerator<T>;
FEnumerator : TEnumerator<T>;
public
constructor Create(const enumerator: TEnumeratorDelegate<T>); overload;
constructor Create(const enumerator: TEnumerator<T>); overload;
constructor Create(const enumerator: IEnumerator<T>); overload;
destructor Destroy; override;
function Aggregate(defaultAggregateValue: TOmniValue;
aggregator: TOmniAggregatorDelegate): IOmniParallelAggregatorLoop<T>;
function AggregateSum: IOmniParallelAggregatorLoop<T>;
function CancelWith(const token: IOmniCancellationToken): IOmniParallelLoop<T>;
function ExecuteAggregate(loopBody: TOmniIteratorIntoDelegate<T>): TOmniValue; overload;
function ExecuteAggregate(loopBody: TOmniIteratorIntoTaskDelegate<T>): TOmniValue; overload;
function IOmniParallelAggregatorLoop<T>.Execute = ExecuteAggregate;
procedure Execute(loopBody: TOmniIteratorDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorTaskDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorIntoDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorIntoTaskDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorStateDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorStateTaskDelegate<T>); overload;
function Finalize(taskFinalizer: TOmniTaskFinalizerDelegate):
IOmniParallelInitializedLoop<T>;
function Initialize(taskInitializer: TOmniTaskInitializerDelegate):
IOmniParallelInitializedLoop<T>;
function Into(const queue: IOmniBlockingCollection): IOmniParallelIntoLoop<T>; overload;
function NoWait: IOmniParallelLoop<T>;
function NumTasks(taskCount: integer): IOmniParallelLoop<T>;
function OnMessage(eventDispatcher: TObject): IOmniParallelLoop<T>; overload;
function OnMessage(msgID: word; eventHandler: TOmniTaskMessageEvent): IOmniParallelLoop<T>; overload;
function OnMessage(msgID: word; eventHandler: TOmniOnMessageFunction): IOmniParallelLoop<T>; overload;
function OnTaskCreate(taskCreateDelegate: TOmniTaskCreateDelegate): IOmniParallelLoop<T>; overload;
function OnTaskCreate(taskCreateDelegate: TOmniTaskControlCreateDelegate): IOmniParallelLoop<T>; overload;
function OnStop(stopCode: TProc): IOmniParallelLoop<T>; overload;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniParallelLoop<T>; overload;
{$IFDEF OTL_FixedGenericIncompletelyDefined}
function OnStopInvoke(stopCode: TProc): IOmniParallelLoop<T>;
{$ENDIF OTL_FixedGenericIncompletelyDefined}
function PreserveOrder: IOmniParallelLoop<T>;
function TaskConfig(const config: IOmniTaskConfig): IOmniParallelLoop<T>;
end; { TOmniParallelLoop<T> }
TOmniParallelSimpleLoop = class(TInterfacedObject, IOmniParallelSimpleLoop)
strict private type
TPartitionInfo = record
LowBound : integer;
HighBound: integer;
end;
TTaskDelegate = reference to procedure (const task: IOmniTask; taskIndex: integer);
strict private
FCancelWith : IOmniCancellationToken;
FCountStopped : IOmniResourceCount;
FFinalizerDelegate : TOmniSimpleTaskFinalizerTaskDelegate;
FFirst : integer;
FInitializerDelegate: TOmniSimpleTaskInitializerTaskDelegate;
FLast : integer;
FNoWait : boolean;
FNumTasks : integer;
FNumTasksManual : boolean;
FOnMessageList : TGpIntegerObjectList;
FOnStop : TOmniTaskStopDelegate;
FPartition : array of TPartitionInfo;
FStep : integer;
FTaskConfig : IOmniTaskConfig;
strict protected
function CreateForTask(taskIndex: integer; const taskDelegate: TTaskDelegate): IOmniTaskControl;
procedure CreatePartitions(var numTasks: integer);
procedure InternalExecute(const taskDelegate: TTaskDelegate);
public
constructor Create(first, last: integer; step: integer = 1);
destructor Destroy; override;
function CancelWith(const token: IOmniCancellationToken): IOmniParallelSimpleLoop;
function NoWait: IOmniParallelSimpleLoop;
function NumTasks(taskCount : integer): IOmniParallelSimpleLoop;
function OnStop(stopCode: TProc): IOmniParallelSimpleLoop; overload;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniParallelSimpleLoop; overload;
function OnStopInvoke(stopCode: TProc): IOmniParallelSimpleLoop;
function TaskConfig(const config: IOmniTaskConfig): IOmniParallelSimpleLoop;
procedure Execute(loopBody: TOmniIteratorSimpleSimpleDelegate); overload;
procedure Execute(loopBody: TOmniIteratorSimpleDelegate); overload;
procedure Execute(loopBody: TOmniIteratorSimpleFullDelegate); overload;
function Initialize(taskInitializer: TOmniSimpleTaskInitializerDelegate): IOmniParallelSimpleLoop; overload;
function Initialize(taskInitializer: TOmniSimpleTaskInitializerTaskDelegate): IOmniParallelSimpleLoop; overload;
function Finalize(taskFinalizer: TOmniSimpleTaskFinalizerDelegate): IOmniParallelSimpleLoop; overload;
function Finalize(taskFinalizer: TOmniSimpleTaskFinalizerTaskDelegate): IOmniParallelSimpleLoop; overload;
function WaitFor(maxWait_ms: cardinal): boolean;
end; { IOmniParallelSimpleLoop }
{$IFDEF OTL_GoodGenerics}
TOmniParallelSimpleLoop<T> = class(TInterfacedObject, IOmniParallelSimpleLoop<T>)
strict private
FData : TArray<T>;
FIterator: IOmniParallelSimpleLoop;
public
constructor Create(const arr: TArray<T>);
function CancelWith(const token: IOmniCancellationToken): IOmniParallelSimpleLoop<T>; inline;
function NoWait: IOmniParallelSimpleLoop<T>; inline;
function NumTasks(taskCount : integer): IOmniParallelSimpleLoop<T>; inline;
function OnStop(stopCode: TProc): IOmniParallelSimpleLoop<T>; overload; inline;
function OnStop(stopCode: TOmniTaskStopDelegate): IOmniParallelSimpleLoop<T>; overload; inline;
function OnStopInvoke(stopCode: TProc): IOmniParallelSimpleLoop<T>;
function TaskConfig(const config: IOmniTaskConfig): IOmniParallelSimpleLoop<T>; inline;
procedure Execute(loopBody: TOmniIteratorSimpleSimpleDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorSimpleDelegate<T>); overload;
procedure Execute(loopBody: TOmniIteratorSimpleFullDelegate<T>); overload;
function Initialize(taskInitializer: TOmniSimpleTaskInitializerDelegate): IOmniParallelSimpleLoop<T>; overload; inline;
function Initialize(taskInitializer: TOmniSimpleTaskInitializerTaskDelegate): IOmniParallelSimpleLoop<T>; overload; inline;
function Finalize(taskFinalizer: TOmniSimpleTaskFinalizerDelegate): IOmniParallelSimpleLoop<T>; overload; inline;
function Finalize(taskFinalizer: TOmniSimpleTaskFinalizerTaskDelegate): IOmniParallelSimpleLoop<T>; overload; inline;
function WaitFor(maxWait_ms: cardinal): boolean; inline;
end; { TOmniParallelSimpleLoop<T> }
{$ENDIF OTL_GoodGenerics}
EJoinException = class(Exception)
strict private
FExceptions: TGpIntegerObjectList;
public type
TJoinInnerException = record
FatalException: Exception;
TaskNumber : integer;
end;
strict protected
function GetInner(idxException: integer): TJoinInnerException;
public
constructor Create; reintroduce;
destructor Destroy; override;
procedure Add(iTask: integer; taskException: Exception);
function Count: integer;
function DetachInner(idxException: integer): Exception;
property Inner[idxException: integer]: TJoinInnerException read GetInner; default;
end; { EJoinException }