-
Notifications
You must be signed in to change notification settings - Fork 140
/
OtlTaskControl.pas
4487 lines (4089 loc) · 169 KB
/
OtlTaskControl.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>Task control encapsulation. Part of the OmniThreadLibrary project.</summary>
///<author>Primoz Gabrijelcic</author>
///<license>
///This software is distributed under the BSD license.
///
///Copyright (c) 2021, 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 : primoz@gabrijelcic.org
/// Blog : http://thedelphigeek.com
/// Contributors : GJ, Lee_Nover, Sean B. Durkin, HHasenack
/// Creation date : 2008-06-12
/// Last modification : 2021-06-22
/// Version : 1.43a
///</para><para>
/// History:
/// 1.43a: 2021-06-22
/// - Prevent 'nil' handlers to be called from TOmniMessageExec.OnMessage.
/// 1.43: 2021-03-10
/// - Implemented IOmniWorker.EventInfo.
/// 1.42: 2020-12-21
/// - [HHasenack] Added IOmniTaskControl.DirectExecute which executes
/// task in the current thread.
/// - IOmniTaskControl.Terminate cancels thread pool tasks with timeout 0.
/// 1.41: 2019-04-26
/// - Implemented IOmniTask.RegisterWaitObject with an anonymous method callback.
/// 1.40c: 2019-03-22
/// - [sglienke] TOmniTaskExecutor.Cleanup clears reference to anonymous function executor.
/// This allows tasks to be run from a package. [issue #132]
/// 1.40b: 2018-12-13
/// - Fixed: If additional wait objects registered with RegisterWaitObject were
/// constantly signalled, timers were never called.
/// 1.40a: 2018-03-16
/// - TOmniMessageExec.OnTerminated checks whether the event handler is assigned
/// before executing it.
/// 1.40: 2017-08-01
/// - Implemented IOmniTask.InvokeOnSelf method.
/// 1.39: 2017-07-26
/// - Implemented support for timer events implemented as TProc and TProc<integer> methods.
/// 1.38b: 2017-04-06
/// - Compiles with Delphi 10.2 Tokyo.
/// 1.38a: 2017-03-28
/// - TOmniTaskExecutor now uses own 64-bit time function. DSiTimeGetTime64 cannot
/// be used for this purpose as its results cannot be compared across threads.
/// 1.38: 2016-07-01
/// - Defined IOmniTaskControl.ProcessorGroup and .NUMANode.
/// - Added support for executing a task in a specific processor group or NUMA node.
/// 1.37: 2015-10-04
/// - Imported mobile support by [Sean].
/// 1.36b: 2015-09-07
/// - Added a debug log (when compiling a Debug build) when TWaitFor.MsgWaitAny
/// returns WAIT_FAILED.
/// 1.36a: 2015-08-28
/// - CheckTimers is no longer called from DispatchOmniMessage if that one was
/// called from CheckTimers.
/// 1.36: 2015-08-27
/// - TOmniWorker message hooks introduced.
/// 1.35: 2014-11-16
/// - IOmniTaskControl can wait on any number of comm handles and wait objects.
/// That enables support for >60 tasks in the OtlThreadPool.
/// 1.34: 2014-11-03
/// - TOmniTaskGroup can now own more than 60 tasks.
/// 1.33a: 2014-09-23
/// - Fixed TOmniTaskControl.SetParameters.
/// 1.33: 2014-09-07
/// - Implemented Run overloads that internally call Invoke to start
/// thread worker.
/// 1.32c: 2014-01-08
/// - Thread priority is set correctly (to 'normal') if it is not explicitly specified.
/// 1.32b: 2013-06-03
/// - Fixed task destruction deadlock introduced in 1.32a.
/// 1.32a: 2013-05-26
/// - Fixed a problem in task destruction sequence.
/// 1.32: 2013-01-30
/// - Added IOmniTaskControl.Stop - signals thread to stop and immediately returns.
/// - Fixed TOmniTaskGroup.TerminateAll.
/// 1.31k: 2012-10-03
/// - Fixed message processing.
/// 1.31j: 2012-10-01
/// - Refactored TOmniTaskExecutor.DispatchEvent a bit more.
/// 1.31i: 2012-09-27
/// - Task controller implements method FilterMessage which allows the event
/// monitor to filter out internal messages.
/// - Removed TOmniTaskControlEventMonitor (no longer needed).
/// 1.31h: 2012-09-24
/// - Fixed bug in TOmniTaskGroup.TerminateAll - maxWait_ms parameter was ignored.
/// 1.31g: 2012-06-18
/// - Fixed race condition in task teardown. Big thanks to [meishier] for putting
/// together a reproducible test case.
/// 1.31f: 2012-04-21
/// - Fixed race condition in InternalStop.
/// 1.31e: 2012-02-07
/// - Bug fixed: Internal event monitor messages must be processed in Terminate,
/// otherwise OnTerminated is not called if the task is terminated from the task
/// controller. Big thanks to [Qmodem] for finding the bug.
/// 1.31d: 2012-02-02
/// - Bug fixed: It was not possible to change timer delay once it was created.
/// Big thanks to [Unspoken] for finding the bug.
/// 1.31c: 2011-12-14
/// - Fixed race condition between TOmniTask.Execute and TOmniTask.Terminate.
/// - Under some circumstances ProcessMessage failed to rebuild handle
/// array before waiting which could cause 'invalid handle' error.
/// 1.31b: 2011-11-08
/// - Fixed invalid "A call to an OS function failed" error in DispatchEvent.
/// 1.31a: 2011-11-06
/// - Fixed wrong order in teardown sequence in TOmniTask.Execute. Great thanks to
/// [Anton Alisov] for providing a reproducible test case.
/// 1.31: 2011-11-05
/// - Adapted to OtlCommon 1.24.
/// 1.30: 2011-11-05
/// - Task parameters are exposed through IOmniTaskControl.Param property.
/// 1.29: 2011-08-27
/// - Implemented another OnTerminated overload acception parameterless anonymous
/// function.
/// 1.28: 2011-07-17
/// - Implemented IOmniTaskControl.DetachException.
/// 1.27: 2011-07-14
/// - IOmniTaskControl implements FatalException property.
/// - Support for non-silent exceptions removed.
/// 1.26a: 2011-07-14
/// - Fixed race condition in TOmniTask.Execute. Big thanks to [Anton Alisov] for
/// providing reproducible test case.
/// 1.26: 2011-07-04
/// - Changed exception handling.
/// 1.25a: 2011-05-27
/// - Passes timer ID to timer proc if it accepts const TOmniValue parameter.
/// 1.25: 2011-04-08
/// - IOmniTaskControl termination empties task message queue and calls appropriate
/// OnMessage handlers.
/// 1.24: 2011-03-16
/// - Implemented IOmniTaskControl.Invoke(procedure) and
/// .Invoke(procedure const task: IOmniTask).
/// - Implemented IOmniTask.Invoke(procedure).
/// 1.23b: 2011-02-28
/// - Bug fixed: Make sure timers are called even if there's a constant stream
/// of messages in registered message queues.
/// 1.23a: 2011-01-07
/// - Bug fixed: Enumerating over TOmniTaskControlList (for example when using
/// IOmniTaskGroup.SendToAll) leaked one object.
/// 1.23: 2010-12-02
/// - Added IOmniTaskControl.CancelWith(token) which can be used to enforce
/// non-default cancellation token.
/// 1.22d: 2010-10-16
/// - Delayed Terminate did not set result.
/// 1.22c: 2010-10-13
/// - Allow Terminate to be called from the OnTerminated handler.
/// 1.22b: 2010-09-21
/// - Better workaround for the 'invalid handle' error.
/// 1.22a: 2010-09-20
/// - Changed the place where internal monitor is destroyed to prevent 'invalid
/// handle' error.
/// 1.22: 2010-07-01
/// - Includes OTLOptions.inc.
/// 1.21c: 2010-06-12
/// - TOmniTaskExecutor must always call Cleanup in case task was not executed.
/// (Issue #19, http://code.google.com/p/omnithreadlibrary/issues/detail?id=19).
/// 1.21b: 2010-05-30
/// - Fixed TOmniTaskControl.WaitFor for pooled tasks.
/// 1.21a: 2010-04-06
/// - [LN] Bug fixed: TOmniTaskControl.WaitFor would hang if thread was
/// terminated externally.
/// 1.21: 2010-03-16
/// - Added support for multiple simultaneous timers. SetTimer takes additional
/// 'timerID' parameter. The old SetTimer assumes timerID = 0.
/// 1.20d: 2010-02-22
/// - D2009 compilation hack moved to OtlCommon.
/// 1.20c: 2010-02-22
/// - A better fix for the D2009 compilation issues, thanks to Serg.
/// 1.20b: 2010-02-21
/// - TOmniTaskControl.otcOnTerminatedExec was not created when OnTerminated
/// function was called with a "reference to function" parameter.
/// - Fixed to compile with D2009.
/// 1.20a: 2010-02-10
/// - Internal message forwarders must be destroyed during task termination.
/// 1.20: 2010-02-09
/// - Added IOmniTaskControl.OnMessage(msgID, handler).
/// 1.19: 2010-02-03
/// - IOmniTaskControl and IOmniTask implement CancellationToken property.
/// 1.18: 2010-02-02
/// - TerminateWhen accepts cancellation token.
/// 1.17: 2010-01-31
/// - Added WithLock overload.
/// 1.16: 2010-01-14
/// - Implemented IOmniTaskControl.UserData[]. The application can store any values
/// in this array. It can be accessed via the integer or string index.
/// 1.15: 2010-01-13
/// - Implemented IOmniTask.GetImplementor.
/// 1.14a: 2009-12-18
/// - Worked around a change in Delphi 2010 update 4.
/// 1.14: 2009-12-12
/// - Implemented support for IOmniTask.RegisterWaitObject/UnregisterWaitObject.
/// 1.13a: 2009-12-12
/// - Raise loud exception for pooled tasks.
/// 1.13: 2009-11-19
/// - Implemented IOmniTaskControl.Unobserved behaviour modifier.
/// 1.12: 2009-11-15
/// - Event monitor notifications implemented with container observer.
/// 1.11a: 2009-11-13
/// - Cleanup in TOmniTask.Execute reordered to fix Issue 13.
/// 1.11: 2009-11-13
/// - Implemented automatic event monitor with methods IOmniTaskControl.OnMessage
/// and OnTerminated. Both support 'procedure of object' and
/// 'reference to procedure' parameters.
/// - D2010 compatibility changes.
/// 1.10: 2009-05-15
/// - Implemented IOmniTaskControl.SilentExceptions.
/// 1.09: 2009-02-08
/// - Implemented per-thread task data storage.
/// 1.08: 2009-01-26
/// - Implemented IOmniTaskControl.Enforced behaviour modifier.
/// - Added TOmniWorker.ProcessMessages - a support for worker to recursively
/// process messages inside message handlers.
/// 1.07: 2009-01-19
/// - Implemented IOmniTaskControlList, a list of IOmniTaskControl interfaces.
/// - TOmniTaskGroup reimplemented using IOmniTaskControlList.
/// 1.06: 2008-12-15
/// - TOmniWorker's internal message loop can now be overridden at various places
/// and even fully replaced with a custom code.
/// 1.05a: 2008-11-17
/// - [Jamie] Fixed bug in TOmniTaskExecutor.Asy_SetTimerInt.
/// 1.05: 2008-11-01
/// - IOmniTaskControl.Terminate kills the task thread if it doesn't terminate in
/// the specified amount of time.
/// 1.04a: 2008-10-06
/// - IOmniTaskControl.Invoke modified to return IOmniTaskControl.
/// 1.04: 2008-10-05
/// - Implemented IOmniTaskControl.Invoke (six overloads), used for string- and
/// pointer-based method dispatch (see demo 18 for more details and demo 19
/// for benchmarks).
/// - Implemented two SetTimer overloads using new invocation methods.
/// - Implemented IOmniTaskControl.SetQueue, which can be used to increase (or
/// reduce) the size of the IOmniTaskControl<->IOmniTask communication queue.
/// This function must be called before .SetMonitor, .RemoveMonitor, .Run or
/// .Schedule.
/// 1.03b: 2008-09-26
/// - More stringent Win32 API result checking.
/// 1.03a: 2008-09-25
/// - Bug fixed: TOmniTaskControl.Schedule always scheduled task to the global
/// thread pool.
/// 1.03: 2008-09-20
/// - Implemented IOmniTaskGroup.SendToAll. This should be looked at as a temporary
/// solution. IOmniTaskGroup should expose communication interface (just like
/// IOmniTask and IOmniTaskControl) but in this case it should be one-to-many
/// queue connecting IOmniTaskGroup's Comm to all tasks inside the group.
/// 1.02: 2008-09-19
/// - Added enumerator to the IOmniTaskGroup interface.
/// - Implemented IOmniTaskGroup.RegisterAllCommWith and .UnregisterAllCommFrom.
/// - Bug fixed in TOmniTaskExecutor.Asy_DispatchMessages - program crashed if
/// communications unregistered inside task's own timer method.
/// - Setting timer interval resets timer countdown.
/// 1.01: 2008-09-18
/// - Implemented SetTimer on the IOmniTask side.
/// - Bug fixed: IOmniTaskGroup.RunAll was not returning a result.
/// 1.0a: 2008-08-29
/// - Bug fixed: .MsgWait was not functional.
/// 1.0: 2008-08-26
/// - First official release.
///</para></remarks>
///Literature
/// - Lock my Object... Please!, Allen Bauer,
/// http://blogs.codegear.com/abauer/2008/02/19/38856
/// - Threading in C#, Joseph Albahari, http://www.albahari.com/threading/
/// - Coordination Data Structures Overview, Emad Omara,
/// http://blogs.msdn.com/pfxteam/archive/2008/06/18/8620615.aspx
/// - Erlang, http://en.wikipedia.org/wiki/Erlang_(programming_language)
/// - A single-word reader/writer spin lock,
/// http://www.bluebytesoftware.com/blog/2009/01/30/ASinglewordReaderwriterSpinLock.aspx
/// - CancellationToken,
/// http://blogs.msdn.com/pfxteam/archive/2009/06/22/9791840.aspx
// TODO 1 -oPrimoz Gabrijelcic : The whole Unobserved mess should go away - task should be implicitly owned ALWAYS
// TODO 3 -oPrimoz Gabrijelcic : Add general way to map unique ID into a task controller/task interface.
// TODO 3 -oPrimoz Gabrijelcic : ChainTo options 'only on success', 'only on fault' (http://blogs.msdn.com/pfxteam/archive/2010/02/09/9960735.aspx)
// TODO 3 -oPrimoz Gabrijelcic : Implement message bus (subscribe/publish)
// http://209.85.129.132/search?q=cache:B2PbIgFSyLcJ:www.dojotoolkit.org/book/dojo-book-0-9/part-3-programmatic-dijit-and-dojo/event-system/publish-and-subscribe-events+dojo+subscribe+publish&hl=sl&client=opera&strip=1
// http://msdn.microsoft.com/en-us/library/ms978583.aspx
// TODO 3 -oPrimoz Gabrijelcic : Could RegisterWaitForSingleObject be used to wait on more than 64 objects at the same time? http://msdn.microsoft.com/en-us/library/ms685061(VS.85).aspx
// TODO 1 -oPrimoz Gabrijelcic : Add cache to TOmniTaskExecutor.DispatchOmniMessage
// TODO 1 -oPrimoz Gabrijelcic : OnTerminated without the 'task' parameter - useful for anonymous functions
unit OtlTaskControl;
{$I OtlOptions.inc}
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
OtlCommon,
{$IFDEF MSWINDOWS}
Windows,
Messages,
DetailedRTTI,
DSiWin32,
GpStuff,
{$ELSE}
Generics.Collections,
{$ENDIF ~MSWINDOWS}
GpLists,
GpStringHash,
SysUtils,
Classes,
SyncObjs,
TypInfo,
OtlSync,
OtlComm,
OtlTask,
OtlContainers,
OtlThreadPool,
OtlContainerObserver;
type
IOmniTaskControl = interface;
TOmniSharedTaskInfo = class;
IOmniTaskControlMonitor = interface ['{20CB3AB7-04D8-454B-AEFE-CFCFF8F27301}']
function Detach(const task: IOmniTaskControl): IOmniTaskControl;
{$IFDEF MSWINDOWS}
function Monitor(const task: IOmniTaskControl): IOmniTaskControl;
{$ENDIF MSWINDOWS}
end; { IOmniTaskControlMonitor }
TOmniWorkerEventInfoType = (etError, etFailed, etIOCompletion, etTimeout, etWinMessage, etMessage, etEvent, etTimer, etWaitObject, etTerminate, etInternal, etUnknown);
TOmniWorkerEventInfo = record
EventType : TOmniWorkerEventInfoType;
TimerID : integer;
WaitObject : integer;
CommChannel: integer;
end; { TOmniWorkerEventInfo }
{$TYPEINFO ON} {$METHODINFO ON}
IOmniWorker = interface ['{CA63E8C2-9B0E-4BFA-A527-31B2FCD8F413}']
function GetImplementor: TObject;
function GetTask: IOmniTask;
procedure SetExecutor(executor: TObject);
procedure SetTask(const value: IOmniTask);
procedure AfterWait(waitFor: TWaitFor; awaited: TWaitFor.TWaitForResult);
procedure BeforeWait(var timeout_ms: cardinal);
function EventInfo(awaited: TWaitFor.TWaitForResult): TOmniWorkerEventInfo;
procedure MessageLoopPayload;
procedure ProcessThreadMessages;
//
procedure Cleanup;
procedure DispatchMessage(var msg: TOmniMessage);
procedure Timer;
function Initialize: boolean;
property Task: IOmniTask read GetTask write SetTask;
property Implementor: TObject read GetImplementor;
end; { IOmniWorker }
TOmniWorker = class(TInterfacedObject, IOmniWorker)
strict private
owExecutor: TObject; {TOmniTaskExecutor}
owTask : IOmniTask;
strict protected
procedure ProcessMessages;
protected //message loop hooks
procedure AfterWait(waitFor: TWaitFor; awaited: TWaitFor.TWaitForResult); virtual;
procedure BeforeWait(var timeout_ms: cardinal); virtual;
procedure DispatchMessage(var msg: TOmniMessage); virtual;
procedure MessageLoopPayload; virtual;
procedure ProcessThreadMessages; virtual;
protected
procedure Cleanup; virtual;
function EventInfo(awaited: TWaitFor.TWaitForResult): TOmniWorkerEventInfo;
function GetImplementor: TObject;
function GetTask: IOmniTask;
function Initialize: boolean; virtual;
procedure SetExecutor(executor: TObject);
procedure SetTask(const value: IOmniTask);
public
procedure Timer; virtual;
property Task: IOmniTask read GetTask write SetTask;
property Implementor: TObject read GetImplementor;
end; { TOmniWorker }
{$TYPEINFO OFF} {$METHODINFO OFF}
TOmniTaskProcedure = procedure(const task: IOmniTask);
TOmniTaskMethod = procedure(const task: IOmniTask) of object;
TOTLThreadPriority = (tpIdle, tpLowest, tpBelowNormal, tpNormal, tpAboveNormal, tpHighest);
IOmniTaskGroup = interface;
TOmniTaskMessageEvent = procedure(const task: IOmniTaskControl; const msg: TOmniMessage) of object;
TOmniTaskTerminatedEvent = procedure(const task: IOmniTaskControl) of object;
{$IFDEF OTL_Anonymous}
TOmniOnMessageFunction = reference to procedure(const task: IOmniTaskControl; const msg: TOmniMessage);
TOmniOnTerminatedFunction = reference to procedure(const task: IOmniTaskControl);
TOmniOnTerminatedFunctionSimple = reference to procedure;
{$ENDIF OTL_Anonymous}
{$IFDEF OTL_Anonymous}
TOmniTaskControlInvokeFunction = reference to procedure;
TOmniTaskControlInvokeFunctionEx = reference to procedure(const task: IOmniTask);
{$ENDIF OTL_Anonymous}
TOmniMessageExec = class
strict protected
omeOnMessage : TOmniExecutable;
omeOnMessageDispatch: TObject;
omeOnTerminated : TOmniExecutable;
public
constructor Create(exec: TOmniTaskMessageEvent); overload;
constructor Create(exec: TOmniTaskTerminatedEvent); overload;
constructor Create(dispatch: TObject); overload;
constructor Clone(exec: TOmniMessageExec);
procedure SetOnMessage(exec: TOmniTaskMessageEvent); overload;
procedure SetOnTerminated(exec: TOmniTaskTerminatedEvent); overload;
procedure OnMessage(const task: IOmniTaskControl; const msg: TOmniMessage);
procedure OnTerminated(const task: IOmniTaskControl);
public
{$IFDEF OTL_Anonymous}
constructor Create(exec: TOmniOnMessageFunction); overload;
constructor Create(exec: TOmniOnTerminatedFunction); overload;
procedure Apply(msgID: word; task: IOmniTaskControl);
procedure SetOnMessage(exec: TOmniOnMessageFunction); overload;
procedure SetOnTerminated(exec: TOmniOnTerminatedFunction); overload;
{$ENDIF OTL_Anonymous}
end; { TOmniMessageExec }
IOmniTaskControl = interface ['{881E94CB-8C36-4CE7-9B31-C24FD8A07556}']
function GetCancellationToken: IOmniCancellationToken;
function GetComm: IOmniCommunicationEndpoint;
function GetExitCode: integer;
function GetExitMessage: string;
function GetLock: TSynchroObject;
function GetName: string;
function GetUniqueID: int64;
function GetUserDataVal(const idxData: TOmniValue): TOmniValue;
procedure SetUserDataVal(const idxData: TOmniValue; const value: TOmniValue);
//
function Alertable: IOmniTaskControl;
function CancelWith(const token: IOmniCancellationToken): IOmniTaskControl;
function ChainTo(const task: IOmniTaskControl; ignoreErrors: boolean = false): IOmniTaskControl;
function ClearTimer(timerID: integer): IOmniTaskControl;
function DetachException: Exception;
/// <summary>
/// Run the task code from within in the calling thread
/// </summary>
function DirectExecute:IOmniTaskControl;
function Enforced(forceExecution: boolean = true): IOmniTaskControl;
function GetFatalException: Exception;
function GetParam: TOmniValueContainer;
function Invoke(const msgMethod: pointer): IOmniTaskControl; overload;
function Invoke(const msgMethod: pointer; msgData: array of const): IOmniTaskControl; overload;
function Invoke(const msgMethod: pointer; msgData: TOmniValue): IOmniTaskControl; overload;
function Invoke(const msgName: string): IOmniTaskControl; overload;
function Invoke(const msgName: string; msgData: array of const): IOmniTaskControl; overload;
function Invoke(const msgName: string; msgData: TOmniValue): IOmniTaskControl; overload;
{$IFDEF OTL_Anonymous}
function Invoke(remoteFunc: TOmniTaskControlInvokeFunction): IOmniTaskControl; overload;
function Invoke(remoteFunc: TOmniTaskControlInvokeFunctionEx): IOmniTaskControl; overload;
{$ENDIF OTL_Anonymous}
function Join(const group: IOmniTaskGroup): IOmniTaskControl;
function Leave(const group: IOmniTaskGroup): IOmniTaskControl;
function MonitorWith(const monitor: IOmniTaskControlMonitor): IOmniTaskControl;
function MsgWait({$IFDEF MSWINDOWS}wakeMask: DWORD = QS_ALLEVENTS{$ELSE}wakeAll: boolean = true{$ENDIF}): IOmniTaskControl;
function NUMANode(numaNodeNumber: integer): IOmniTaskControl;
function OnMessage(eventDispatcher: TObject): IOmniTaskControl; overload;
function OnMessage(eventHandler: TOmniTaskMessageEvent): IOmniTaskControl; overload;
function OnMessage(msgID: word; eventHandler: TOmniTaskMessageEvent): IOmniTaskControl; overload;
function OnMessage(msgID: word; eventHandler: TOmniMessageExec): IOmniTaskControl; overload;
{$IFDEF OTL_Anonymous}
function OnMessage(eventHandler: TOmniOnMessageFunction): IOmniTaskControl; overload;
function OnMessage(msgID: word; eventHandler: TOmniOnMessageFunction): IOmniTaskControl; overload;
function OnTerminated(eventHandler: TOmniOnTerminatedFunction): IOmniTaskControl; overload;
function OnTerminated(eventHandler: TOmniOnTerminatedFunctionSimple): IOmniTaskControl; overload;
{$ENDIF OTL_Anonymous}
function OnTerminated(eventHandler: TOmniTaskTerminatedEvent): IOmniTaskControl; overload;
function ProcessorGroup(procGroupNumber: integer): IOmniTaskControl;
function RemoveMonitor: IOmniTaskControl;
function Run: IOmniTaskControl; overload;
function Run(const msgMethod: pointer): IOmniTaskControl; overload;
function Run(const msgMethod: pointer; msgData: array of const): IOmniTaskControl; overload;
function Run(const msgMethod: pointer; msgData: TOmniValue): IOmniTaskControl; overload;
function Run(const msgName: string): IOmniTaskControl; overload;
function Run(const msgName: string; msgData: array of const): IOmniTaskControl; overload;
function Run(const msgName: string; msgData: TOmniValue): IOmniTaskControl; overload;
{$IFDEF OTL_Anonymous}
function Run(remoteFunc: TOmniTaskControlInvokeFunction): IOmniTaskControl; overload;
function Run(remoteFunc: TOmniTaskControlInvokeFunctionEx): IOmniTaskControl; overload;
{$ENDIF OTL_Anonymous}
function Schedule(const threadPool: IOmniThreadPool = nil {default pool}): IOmniTaskControl;
{$IFDEF MSWINDOWS}
function SetMonitor(hWindow: THandle): IOmniTaskControl;
{$ENDIF MSWINDOWS}
function SetParameter(const paramName: string; const paramValue: TOmniValue): IOmniTaskControl; overload;
function SetParameter(const paramValue: TOmniValue): IOmniTaskControl; overload;
function SetParameters(const parameters: array of TOmniValue): IOmniTaskControl;
function SetPriority(threadPriority: TOTLThreadPriority): IOmniTaskControl;
function SetQueueSize(numMessages: integer): IOmniTaskControl;
function SetTimer(interval_ms: cardinal): IOmniTaskControl; overload; deprecated {$IFDEF Unicode}'use three-parameter version'{$ENDIF Unicode};
function SetTimer(interval_ms: cardinal; const timerMessage: TOmniMessageID): IOmniTaskControl; overload; deprecated {$IFDEF Unicode}'use three-parameter version'{$ENDIF Unicode};
function SetTimer(timerID: integer; interval_ms: cardinal; const timerMessage: TOmniMessageID): IOmniTaskControl; overload;
{$IFDEF OTL_Anonymous}
function SetTimer(timerID: integer; interval_ms: cardinal; const timerMessage: TProc): IOmniTaskControl; overload;
function SetTimer(timerID: integer; interval_ms: cardinal; const timerMessage: TProc<integer>): IOmniTaskControl; overload;
{$ENDIF OTL_Anonymous}
function SetUserData(const idxData: TOmniValue; const value: TOmniValue): IOmniTaskControl;
procedure Stop;
function Terminate(maxWait_ms: cardinal = INFINITE): boolean; //will kill thread after timeout
function TerminateWhen(event: TOmniTransitionEvent): IOmniTaskControl; overload;
function TerminateWhen(token: IOmniCancellationToken): IOmniTaskControl; overload;
function Unobserved: IOmniTaskControl;
function WaitFor(maxWait_ms: cardinal): boolean;
function WaitForInit: boolean;
function WithCounter(const counter: IOmniCounter): IOmniTaskControl;
function WithLock(const lock: TSynchroObject; autoDestroyLock: boolean = true): IOmniTaskControl; overload;
function WithLock(const lock: IOmniCriticalSection): IOmniTaskControl; overload;
//
property CancellationToken: IOmniCancellationToken read GetCancellationToken;
property Comm: IOmniCommunicationEndpoint read GetComm;
property ExitCode: integer read GetExitCode;
property ExitMessage: string read GetExitMessage;
property FatalException: Exception read GetFatalException;
property Lock: TSynchroObject read GetLock;
property Name: string read GetName;
property Param: TOmniValueContainer read GetParam;
property UniqueID: int64 read GetUniqueID;
property UserData[const idxData: TOmniValue]: TOmniValue read GetUserDataVal write SetUserDataVal;
end; { IOmniTaskControl }
// Implementation details, needed by the OtlEventMonitor. Not for public consumption.
IOmniTaskControlSharedInfo = interface(IOmniTaskControl) ['{5C3262CC-C941-406B-81CC-0E3B608E9077}']
function GetSharedInfo: TOmniSharedTaskInfo;
//
property SharedInfo: TOmniSharedTaskInfo read GetSharedInfo;
end; { IOmniTaskControlSharedInfo }
IOmniTaskControlListEnumerator = interface
function GetCurrent: IOmniTaskControl;
function MoveNext: boolean;
property Current: IOmniTaskControl read GetCurrent;
end; { IOmniTaskControlListEnumerator }
IOmniTaskControlList = interface
function Get(idxItem: integer): IOmniTaskControl;
function GetCapacity: integer;
function GetCount: integer;
procedure Put(idxItem: integer; const value: IOmniTaskControl);
procedure SetCapacity(const value: integer);
procedure SetCount(const value: integer);
//
function Add(const item: IOmniTaskControl): integer;
procedure Clear;
procedure Delete(idxItem: integer);
procedure Exchange(idxItem1, idxItem2: integer);
function First: IOmniTaskControl;
function GetEnumerator: IOmniTaskControlListEnumerator;
function IndexOf(const item: IOmniTaskControl): integer;
function IndexOfID(uniqueID: int64): integer;
procedure Insert(idxItem: integer; const item: IOmniTaskControl);
function Last: IOmniTaskControl;
function Remove(const item: IOmniTaskControl): integer;
function RemoveByID(uniqueID: int64): integer;
property Capacity: Integer read GetCapacity write SetCapacity;
property Count: integer read GetCount write SetCount;
property Items[idxItem: integer]: IOmniTaskControl read Get write Put; default;
end; { IOmniTaskControlList }
//v1.1 extensions:
// maybe: Comm: IOmniCommunicationEndpoint, which is actually one-to-many-to-one
// function Sequential: IOmniTaskGroup;
// function Parallel(useThreadPool: IOmniThreadPool): IOmniTaskGroup;
// maybe: if one of group processes dies, TerminateAll should automatically happen?
IOmniTaskGroup = interface ['{B36C08B4-0F71-422C-8613-63C4D04676B7}']
function GetTasks: IOmniTaskControlList;
//
function Add(const taskControl: IOmniTaskControl): IOmniTaskGroup;
function GetEnumerator: IOmniTaskControlListEnumerator;
function RegisterAllCommWith(const task: IOmniTask): IOmniTaskGroup;
function Remove(const taskControl: IOmniTaskControl): IOmniTaskGroup;
function RunAll: IOmniTaskGroup;
procedure SendToAll(const msg: TOmniMessage);
function TerminateAll(maxWait_ms: cardinal = INFINITE): boolean;
function UnregisterAllCommFrom(const task: IOmniTask): IOmniTaskGroup;
function WaitForAll(maxWait_ms: cardinal = INFINITE): boolean;
property Tasks: IOmniTaskControlList read GetTasks;
end; { IOmniTaskGroup }
TOmniSharedTaskInfo = class
strict private
ostiCancellationToken : IOmniCancellationToken; // must be the first field for alignment
strict private
ostiChainIgnoreErrors : boolean;
ostiChainTo : IOmniTaskControl;
ostiCommChannel : IOmniTwoWayChannel;
ostiCounter : IOmniCounter;
ostiLock : TSynchroObject;
{$IFDEF MSWINDOWS}
ostiMonitor : TOmniContainerWindowsMessageObserver;
{$ENDIF MSWINDOWS}
ostiMonitorLock : TOmniCS;
ostiNUMANode : integer;
ostiProcessorGroup : integer;
ostiStopped : boolean;
ostiTaskName : string;
ostiTerminatedEvent : TOmniTransitionEvent;
ostiTerminateEvent : TOmniTransitionEvent;
ostiTerminating : boolean;
ostiUniqueID : int64;
strict protected
function GetCancellationToken: IOmniCancellationToken;
protected
procedure SetCancellationToken(const token: IOmniCancellationToken);
public
constructor Create;
property CancellationToken: IOmniCancellationToken read GetCancellationToken;
property ChainIgnoreErrors: boolean read ostiChainIgnoreErrors write ostiChainIgnoreErrors;
property ChainTo: IOmniTaskControl read ostiChainTo write ostiChainTo;
property CommChannel: IOmniTwoWayChannel read ostiCommChannel write ostiCommChannel;
property Counter: IOmniCounter read ostiCounter write ostiCounter;
property Lock: TSynchroObject read ostiLock write ostiLock;
{$IFDEF MSWINDOWS}
property Monitor: TOmniContainerWindowsMessageObserver read ostiMonitor write ostiMonitor;
{$ENDIF MSWINDOWS}
property MonitorLock: TOmniCS read ostiMonitorLock;
property NUMANode: integer read ostiNUMANode write ostiNUMANode;
property ProcessorGroup: integer read ostiProcessorGroup write ostiProcessorGroup;
property Stopped: boolean read ostiStopped write ostiStopped;
property TaskName: string read ostiTaskName write ostiTaskName;
property TerminatedEvent: TOmniTransitionEvent read ostiTerminatedEvent write ostiTerminatedEvent;
property TerminateEvent: TOmniTransitionEvent read ostiTerminateEvent write ostiTerminateEvent;
property Terminating: boolean read ostiTerminating write ostiTerminating;
property UniqueID: int64 read ostiUniqueID write ostiUniqueID;
end; { TOmniSharedTaskInfo }
function CreateTask(worker: TOmniTaskProcedure; const taskName: string = ''): IOmniTaskControl; overload;
function CreateTask(worker: TOmniTaskMethod; const taskName: string = ''): IOmniTaskControl; overload;
function CreateTask(const worker: IOmniWorker; const taskName: string = ''): IOmniTaskControl; overload;
// function CreateTask(worker: IOmniTaskGroup; const taskName: string = ''): IOmniTaskControl; overload;
{$IFDEF OTL_Anonymous}
function CreateTask(worker: TOmniTaskDelegate; const taskName: string = ''): IOmniTaskControl; overload;
{$ENDIF OTL_Anonymous}
function CreateTaskGroup: IOmniTaskGroup;
function CreateTaskControlList: IOmniTaskControlList;
type
TOmniInternalMessageType = (imtStringMsg, imtAddressMsg, imtFuncMsg, imtAnonMsg);
TOmniInternalMessage = class
strict private
imInternalMessageType: TOmniInternalMessageType;
public
class function InternalType(const msg: TOmniMessage): TOmniInternalMessageType;
constructor Create(internalMessageType: TOmniInternalMessageType);
property InternalMessageType: TOmniInternalMessageType read imInternalMessageType;
end; { TOmniInternalMessage }
TOmniInternalStringMsg = class(TOmniInternalMessage)
strict private
ismMsgData: TOmniValue;
ismMsgName: string;
public
class function CreateMessage(const msgName: string; msgData: TOmniValue): TOmniMessage; inline;
class procedure UnpackMessage(const msg: TOmniMessage; var msgName: string;
var msgData: TOmniValue); inline;
constructor Create(const msgName: string; const msgData: TOmniValue);
property MsgData: TOmniValue read ismMsgData;
property MsgName: string read ismMsgName;
end; { TOmniInternalStringMsg }
TOmniInternalAddressMsg = class(TOmniInternalMessage)
strict private
ismMsgData : TOmniValue;
ismMsgMethod: pointer;
public
class function CreateMessage(const msgMethod: pointer; msgData: TOmniValue):
TOmniMessage; inline;
class procedure UnpackMessage(const msg: TOmniMessage; var msgMethod: pointer; var
msgData: TOmniValue); inline;
constructor Create(const msgMethod: pointer; const msgData: TOmniValue);
property MsgData: TOmniValue read ismMsgData;
property MsgMethod: pointer read ismMsgMethod;
end; { TOmniInternalAddressMsg }
{$IFDEF OTL_Anonymous}
TOmniInternalAnonMsg = class(TOmniInternalMessage)
strict private
ismMsgData: TOmniValue;
ismMsgProc: TProc<integer>;
public
class function CreateMessage(const msgAnon: TProc<integer>; msgData: TOmniValue): TOmniMessage; inline;
class procedure UnpackMessage(const msg: TOmniMessage; var msgAnon: TProc<integer>;
var msgData: TOmniValue); inline;
constructor Create(const msgAnon: TProc<integer>; const msgData: TOmniValue);
property MsgData: TOmniValue read ismMsgData;
property MsgProc: TProc<integer> read ismMsgProc;
end; { TOmniInternalAnonMsg }
TOmniInternalFuncMsg = class(TOmniInternalMessage)
strict private
ifmFunc : TOmniTaskControlInvokeFunction;
ifmFuncEx : TOmniTaskControlInvokeFunctionEx;
ifmTaskFunc: TOmniTaskInvokeFunction;
public
class function CreateMessage(func: TOmniTaskControlInvokeFunction): TOmniMessage;
overload; inline;
class function CreateMessage(func: TOmniTaskControlInvokeFunctionEx): TOmniMessage; overload; inline;
class function CreateMessage(func: TOmniTaskInvokeFunction): TOmniMessage; overload;
inline;
class procedure UnpackMessage(const msg: TOmniMessage;
var func: TOmniTaskControlInvokeFunction; var funcEx: TOmniTaskControlInvokeFunctionEx;
var taskFunc: TOmniTaskInvokeFunction); overload;
class function UnpackMessage(const msg: TOmniMessage; var func: TOmniTaskInvokeFunction):
boolean; overload;
constructor Create(func: TOmniTaskControlInvokeFunction); overload;
constructor Create(func: TOmniTaskControlInvokeFunctionEx); overload;
constructor Create(func: TOmniTaskInvokeFunction); overload;
property Func: TOmniTaskControlInvokeFunction read ifmFunc;
property FuncEx: TOmniTaskControlInvokeFunctionEx read ifmFuncEx;
property TaskFunc: TOmniTaskInvokeFunction read ifmTaskFunc;
end; { TOmniInternalFuncMsg }
{$ENDIF OTL_Anonymous}
TOmniInvokeType = (itUnknown, itSelf, itSelfAndOmniValue, itSelfAndObject);
TOmniInvokeSignature_Self = procedure(Self: TObject);
TOmniInvokeSignature_Self_OmniValue = procedure(Self: TObject; var value: TOmniValue);
TOmniInvokeSignature_Self_Object = procedure(Self: TObject; var obj: TObject);
TOmniInvokeInfo = class
strict private
oiiAddress : pointer;
oiiSignature: TOmniInvokeType;
public
constructor Create(methodAddr: pointer; methodSignature: TOmniInvokeType);
property Address: pointer read oiiAddress;
property Signature: TOmniInvokeType read oiiSignature;
end; { TOmniInvokeInfo }
TOmniTaskControlOption = (tcoAlertableWait, tcoMessageWait, tcoForceExecution);
TOmniTaskControlOptions = set of TOmniTaskControlOption;
TOmniExecutorType = (etNone, etMethod, etProcedure, etWorker, etFunction);
TOmniTaskTimerInfo = class
strict private
ottiInterval_ms: cardinal;
ottiMessageID : TOmniMessageID;
ottiTimerID : integer;
public
constructor Create(timerID: integer; interval_ms: cardinal; messageID: TOmniMessageID);
property Interval_ms: cardinal read ottiInterval_ms write ottiInterval_ms;
property MessageID: TOmniMessageID read ottiMessageID write ottiMessageID;
property TimerID: integer read ottiTimerID write ottiTimerID;
end; { TOmniTaskTimerInfo }
TOmniTaskControl = class;
TOmniTaskExecutor = class
strict private type
TOmniMessageInfo = record
IdxFirstMessage : integer;
IdxFirstTerminate : integer;
IdxFirstWaitObject: integer;
IdxLastMessage : integer;
IdxLastTerminate : integer;
IdxLastWaitObject : integer;
IdxRebuildHandles : integer;
NewMessageEvent : TOmniTransitionEvent;
NumWaitHandles : integer;
WaitHandles : {$IFDEF MSWINDOWS}array of THandle{$ELSE}TOmniSynchroArray{$ENDIF};
Waiter : TWaitFor;
{$IFDEF MSWINDOWS}
WaitFlags : DWORD;
WaitWakeMask : DWORD;
{$ELSE}
WaitWakeAll : boolean;
{$ENDIF ~MSWINDOWS}
function AsString: string;
{$IFNDEF MSWINDOWS}
function GetSynchroIndex(WaitResult: TWaitResult; const Handle: IOmniSynchro): integer;
{$ENDIF ~MSWINDOWS}
end;
strict private // those must be 4-aligned, keep them on the top
oteInternalLock : TOmniCS;
oteOptionsLock : TOmniCS;
oteTimerLock : TOmniCS;
strict private
oteCommList : TInterfaceList;
oteCommNewMsgList : {$IFDEF MSWINDOWS}TGpInt64List{$ELSE}TList<IOmniEvent>{$ENDIF};
oteCommRebuildHandles: TOmniTransitionEvent;
oteException : Exception;
oteExecutorType : TOmniExecutorType;
oteExitCode : TOmniAlignedInt32;
oteExitMessage : string;
{$IFDEF OTL_Anonymous}
oteFunc : TOmniTaskDelegate;
{$ENDIF OTL_Anonymous}
oteMethod : TOmniTaskMethod;
oteMethodHash : TGpStringObjectHash;
oteMsgInfo : TOmniMessageInfo;
oteOptions : TOmniTaskControlOptions;
oteOwner_ref : TOmniTaskControl;
otePriority : TOTLThreadPriority;
oteProc : TOmniTaskProcedure;
oteTerminateHandles : {$IFDEF MSWINDOWS}TGpInt64List{$ELSE}TOmniSynchroArray{$ENDIF};
oteLastTimeGetTime64 : int64;
oteTerminating : boolean;
oteTimeGetTime64Base : int64;
oteTimers : TGpInt64ObjectList;
{$IFDEF MSWINDOWS}
oteWakeMask : DWORD;
{$ELSE}
oteWakeAll : boolean;
{$ENDIF ~MSWINDOWS}
oteWaitHandlesGen : int64;
oteWaitObjectList : TOmniWaitObjectList;
oteWorkerInitialized : TOmniTransitionEvent;
oteWorkerInitOK : boolean;
oteWorkerIntf : IOmniWorker;
strict protected
procedure CallOmniTimer;
procedure CheckTimers;
procedure Cleanup;
procedure DispatchCommMessage(newMsgHandle: TOmniTransitionEvent;
const task: IOmniTask; var msgInfo: TOmniMessageInfo);
procedure DispatchMessages(const task: IOmniTask);
function GetExitCode: integer; inline;
function GetExitMessage: string;
function GetImplementor: TObject;
procedure GetMethodAddrAndSignature(const methodName: string;
var methodAddress: pointer; var methodSignature: TOmniInvokeType);
procedure GetMethodNameFromInternalMessage(const msg: TOmniMessage; var msgName: string;
var msgData: TOmniValue {$IFDEF OTL_Anonymous};
var func: TOmniTaskControlInvokeFunction; var funcEx: TOmniTaskControlInvokeFunctionEx;
var proc: TProc<integer>; var taskFunc: TOmniTaskInvokeFunction {$ENDIF OTL_Anonymous});
function GetOptions: TOmniTaskControlOptions;
function HaveElapsedTimer: boolean;
procedure Initialize;
procedure InsertTimer(wakeUpTime_ms: int64; timerInfo: TOmniTaskTimerInfo);
function LocateTimer(timerID: integer): integer;
{$IFDEF MSWINDOWS}
procedure ProcessThreadMessages;
{$ENDIF MSWINDOWS}
procedure RaiseInvalidSignature(const methodName: string);
procedure RemoveTerminationEvents(const srcMsgInfo: TOmniMessageInfo; var dstMsgInfo:
TOmniMessageInfo);
procedure ReportInvalidHandle(msgInfo: TOmniMessageInfo);
procedure SetOptions(const value: TOmniTaskControlOptions);
procedure SetTimer(timerID: integer; interval_ms: cardinal; const timerMessage: TOmniMessageID);
function TestForInternalRebuild(const task: IOmniTask;
var msgInfo: TOmniMessageInfo): boolean;
function TimeGetTime64: int64;
protected
function DispatchEvent(awaited: TWaitFor.TWaitForResult; const task: IOmniTask;
var msgInfo: TOmniMessageInfo{$IFNDEF MSWINDOWS}; SignalEvent: IOmnIEvent{$ENDIF}): boolean; virtual;
procedure DispatchOmniMessage(msg: TOmniMessage; doCheckTimers: boolean); virtual;
function EventInfo(awaited: TWaitFor.TWaitForResult): TOmniWorkerEventInfo;
procedure MainMessageLoop(const task: IOmniTask; var msgInfo: TOmniMessageInfo); virtual;
procedure MessageLoopPayload; virtual;
procedure ProcessMessages(task: IOmniTask); virtual;
procedure RebuildWaitHandles(const task: IOmniTask; var msgInfo: TOmniMessageInfo); virtual;
function TimeUntilNextTimer_ms: cardinal; virtual;
function WaitForEvent(const msgInfo: TOmniMessageInfo; timeout_ms: cardinal
{$IFNDEF MSWINDOWS}; var SignalEvent: IOmniEvent{$ENDIF}): TWaitFor.TWaitForResult; virtual;
public
constructor Create(owner_ref: TOmniTaskControl; const workerIntf: IOmniWorker); overload;
constructor Create(owner_ref: TOmniTaskControl; method: TOmniTaskMethod); overload;
constructor Create(owner_ref: TOmniTaskControl; proc: TOmniTaskProcedure); overload;
{$IFDEF OTL_Anonymous}
constructor Create(owner_ref: TOmniTaskControl; func: TOmniTaskDelegate); overload;
{$ENDIF OTL_Anonymous}
destructor Destroy; override;
procedure Asy_Execute(const task: IOmniTask);
procedure Asy_RegisterComm(const comm: IOmniCommunicationEndpoint);
procedure Asy_RegisterWaitObject(waitObject: TOmniTransitionEvent; responseHandler: TOmniWaitObjectMethod); overload;
{$IFDEF OTL_Anonymous}
procedure Asy_RegisterWaitObject(waitObject: TOmniTransitionEvent; responseHandler: TOmniWaitObjectProc); overload;
{$ENDIF OTL_Anonymous}
procedure Asy_SetExitStatus(exitCode: integer; const exitMessage: string);
procedure SetProcessorGroup(procGroupNumber: integer);
procedure SetNUMANode(numaNodeNumber: integer);
procedure Asy_SetTimer(timerID: integer; interval_ms: cardinal; const timerMessage:
TOmniMessageID); overload;
procedure Asy_UnregisterComm(const comm: IOmniCommunicationEndpoint);
procedure Asy_UnregisterWaitObject(waitObject: TOmniTransitionEvent);
procedure EmptyMessageQueues(const task: IOmniTask);
procedure TerminateWhen(handle: TOmniTransitionEvent); overload;
{$IFDEF OTL_NUMASupport}
class function VerifyNUMANode(numaNodeNumber: integer): IOmniNUMANode;
class procedure VerifyProcessorGroup(procGroupNumber: integer);
{$ENDIF OTL_NUMASupport}
function WaitForInit: boolean;
property ExitCode: integer read GetExitCode;
property ExitMessage: string read GetExitMessage;
property Implementor: TObject read GetImplementor;
property Options: TOmniTaskControlOptions read GetOptions write SetOptions;
property Priority: TOTLThreadPriority read otePriority write otePriority;
property TaskException: Exception read oteException write oteException;
property Terminating: boolean read oteTerminating write oteTerminating;
{$IFDEF MSWINDOWS}
property WakeMask: DWORD read oteWakeMask write oteWakeMask;
{$ELSE}
property WakeAll: boolean read oteWakeAll write oteWakeAll;
{$ENDIF ~MSWINDOWS}
property WorkerInitialized: TOmniTransitionEvent read oteWorkerInitialized;
property WorkerInitOK: boolean read oteWorkerInitOK;
property WorkerIntf: IOmniWorker read oteWorkerIntf;
end; { TOmniTaskExecutor }
TOmniTask = class(TInterfacedObject, IOmniTask, IOmniTaskExecutor)
strict private
otCleanupLock : TOmniMREW;
otExecuting : boolean;
otExecutor_ref : TOmniTaskExecutor;
otParameters_ref : TOmniValueContainer;
otSharedInfo_ref : TOmniSharedTaskInfo;
otTerminateWillCallExecute: boolean;
otThreadData : IInterface;
otThreadID : TThreadID;
protected
function GetCancellationToken: IOmniCancellationToken; inline;
function GetComm: IOmniCommunicationEndpoint; inline;
function GetCounter: IOmniCounter;
function GetImplementor: TObject;
function GetLock: TSynchroObject;
function GetName: string; inline;
function GetParam: TOmniValueContainer; inline;
function GetTerminateEvent: TOmniTransitionEvent; inline;
function GetThreadData: IInterface; inline;
function GetUniqueID: int64; inline;
procedure InternalExecute(calledFromTerminate: boolean);
procedure SetThreadData(const value: IInterface); inline;
procedure Terminate;
public
constructor Create(executor: TOmniTaskExecutor; parameters: TOmniValueContainer;
sharedInfo: TOmniSharedTaskInfo);
procedure ClearTimer(timerID: integer = 0);
procedure Enforced(forceExecution: boolean = true);
procedure Execute;
{$IFDEF OTL_Anonymous}
procedure Invoke(remoteFunc: TOmniTaskInvokeFunction);
procedure InvokeOnSelf(remoteFunc: TOmniTaskInvokeFunction);
{$ENDIF OTL_Anonymous}
procedure RegisterComm(const comm: IOmniCommunicationEndpoint);
procedure RegisterWaitObject(waitObject: TOmniTransitionEvent; responseHandler: TOmniWaitObjectMethod); overload;
{$IFDEF OTL_Anonymous}
procedure RegisterWaitObject(waitObject: TOmniTransitionEvent; responseHandler: TOmniWaitObjectProc); overload;
{$ENDIF OTL_Anonymous}
procedure SetException(exceptionObject: pointer);
procedure SetExitStatus(exitCode: integer; const exitMessage: string);
procedure SetProcessorGroup(procGroupNumber: integer);
procedure SetNUMANode(numaNodeNumber: integer);
procedure SetTimer(interval_ms: cardinal); overload;
procedure SetTimer(interval_ms: cardinal; const timerMessage: TOmniMessageID); overload;
procedure SetTimer(timerID: integer; interval_ms: cardinal; const timerMessage: TOmniMessageID); overload;
{$IFDEF OTL_Anonymous}
procedure SetTimer(timerID: integer; interval_ms: cardinal; const timerMessage: TProc); overload;
procedure SetTimer(timerID: integer; interval_ms: cardinal; const timerMessage: TProc<integer>); overload;
{$ENDIF OTL_Anonymous}
function Stopped: boolean;
procedure StopTimer;
function Terminated: boolean;
procedure UnregisterComm(const comm: IOmniCommunicationEndpoint);
procedure UnregisterWaitObject(waitObject: TOmniTransitionEvent);
property CancellationToken: IOmniCancellationToken read GetCancellationToken;
property Comm: IOmniCommunicationEndpoint read GetComm;
property Counter: IOmniCounter read GetCounter;
property Implementor: TObject read GetImplementor;
property Lock: TSynchroObject read GetLock;
property Name: string read GetName;
property Param: TOmniValueContainer read GetParam;
property SharedInfo: TOmniSharedTaskInfo read otSharedInfo_ref;
property TerminateEvent: TOmniTransitionEvent read GetTerminateEvent;
property ThreadData: IInterface read GetThreadData;
property UniqueID: int64 read GetUniqueID;