-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
ConcurrentTasks.pas
1518 lines (1317 loc) · 52.6 KB
/
ConcurrentTasks.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
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
Concurrent tasks
Small library providing means for running and controlling multiple separate
tasks run in threads (each task in its own thread).
To use this unit, create a descendant of class TCNTSTask and put the
main processing code into method Main (override it). Then pass instance of
this class to an instance of TCNTSManager. Manager will automatically start
the task when running resources get available, or you can start the task
manually (this can pause other task if there are no running slots
available).
You can call any public method of TCNTSTask from Main, but remember that
the code is running in its own thread, so protect any shared data you want
to access, tasks don't have any mean of thread safety and data integrity
protection.
In Main, you should call method Cycle regularly, this ensures the task
responds to requests from the manager and also enables the intergrated
messaging system (which is also used for progress signalling). If you want
to react to incoming messages, override task's protected method
ProcessMessage.
Remember that the messaging system is strictly server-client in nature.
Meaning any message sent from a task will arrive to the manager. To enable
message processing and progress reporting in the manager, make sure to call
method Update regularly (this method receives and dispatches messages sent
from all individual tasks).
The implementation of method Main is entirely up to you, but suggested
template would be as follows:
Function TTestTask.Main: Boolean;
begin
while not Terminated do
begin
Cycle;
[user code]
[progress signalling]
end;
Result := not Terminated;
end;
Version 1.2.1 (2024-05-03)
Last change 2024-09-09
©2017-2024 František Milt
Contacts:
František Milt: frantisek.milt@gmail.com
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.ConcurrentTasks
Dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
* AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
CrossSyncObjs - github.com/TheLazyTomcat/Lib.CrossSyncObjs
InterlockedOps - github.com/TheLazyTomcat/Lib.InterlockedOps
Messanger - github.com/TheLazyTomcat/Lib.Messanger
Library AuxExceptions is required only when rebasing local exception classes
(see symbol ConcurrentTasks_UseAuxExceptions for details).
Library AuxExceptions might also be required as an indirect dependency.
Indirect dependencies:
BasicUIM - github.com/TheLazyTomcat/Lib.BasicUIM
BinaryStreamingLite - github.com/TheLazyTomcat/Lib.BinaryStreamingLite
BitOps - github.com/TheLazyTomcat/Lib.BitOps
BitVector - github.com/TheLazyTomcat/Lib.BitVector
HashBase - github.com/TheLazyTomcat/Lib.HashBase
LinSyncObjs - github.com/TheLazyTomcat/Lib.LinSyncObjs
ListSorters - github.com/TheLazyTomcat/Lib.ListSorters
MemVector - github.com/TheLazyTomcat/Lib.MemVector
NamedSharedItems - github.com/TheLazyTomcat/Lib.NamedSharedItems
SHA1 - github.com/TheLazyTomcat/Lib.SHA1
SharedMemoryStream - github.com/TheLazyTomcat/Lib.SharedMemoryStream
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
SimpleFutex - github.com/TheLazyTomcat/Lib.SimpleFutex
StaticMemoryStream - github.com/TheLazyTomcat/Lib.StaticMemoryStream
StrRect - github.com/TheLazyTomcat/Lib.StrRect
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
WinSyncObjs - github.com/TheLazyTomcat/Lib.WinSyncObjs
===============================================================================}
unit ConcurrentTasks;
{
ConcurrentTasks_UseAuxExceptions
If you want library-specific exceptions to be based on more advanced classes
provided by AuxExceptions library instead of basic Exception class, and don't
want to or cannot change code in this unit, you can define global symbol
ConcurrentTasks_UseAuxExceptions to achieve this.
}
{$IF Defined(ConcurrentTasks_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IF Defined(WINDOWS) or Defined(MSWINDOWS)}
{$DEFINE Windows}
{$ELSEIF Defined(LINUX) and Defined(FPC)}
{$DEFINE Linux}
{$ELSE}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}
{$MODESWITCH ClassicProcVars+}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
{$H+}
interface
uses
SysUtils, Classes,
AuxTypes, AuxClasses, Messanger, CrossSyncObjs
{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Library-specific exceptions
===============================================================================}
type
ECNSTException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
ECNSTIndexOutOfBounds = class(ECNSTException);
ECNTSInvalidValue = class(ECNSTException);
ECNTSTaskRunning = class(ECNSTException);
{===============================================================================
--------------------------------------------------------------------------------
TCNTSTask
--------------------------------------------------------------------------------
===============================================================================}
type
TCNTSTaskID = Integer;
// messaging types
TCNTSMessageParam = TMsgrParam;
TCNTSMessageResult = TMsgrParam;
TCNTSMessage = record
Param1: TCNTSMessageParam;
Param2: TCNTSMessageParam;
Result: TCNTSMessageResult;
end;
{===============================================================================
TCNTSTask - class declaration
===============================================================================}
type
TCNTSTask = class(TCustomObject)
protected
fTaskID: TCNTSTaskID;
fCommEndpoint: TMessangerEndpoint;
fPauseEvent: TEvent;
fTerminated: Integer;
// getters, setters
Function GetTerminated: Boolean;
procedure SetTerminated(Value: Boolean);
// internal methods (not to be called from user code)
procedure InternalMessageHandler(Sender: TObject; Msg: TMsgrMessageIn; var Flags: TMsgrDispatchFlags); virtual;
procedure InternalSetup(TaskID: TCNTSTaskID; CommEndpoint: TMessangerEndpoint; PauseEvent: TEvent); virtual;
procedure InternalExecute; virtual;
// protected user methods
procedure ProcessMessage(var Msg: TCNTSMessage); virtual;
public
// public user methods
Function Main: Boolean; virtual; abstract;
// other public methods
procedure Terminate; virtual;
Function PostMessage(Param1,Param2: TCNTSMessageParam): Boolean; virtual;
Function SendMessage(Param1,Param2: TCNTSMessageParam): TCNTSMessageResult; virtual;
procedure SignalStageProgress(Stage: Integer; Progress: Double); virtual;
procedure SignalProgress(Progress: Double); virtual;
procedure Cycle(Timeout: UInt32 = 0); virtual;
// properties
property TaskID: TCNTSTaskID read fTaskID;
property Terminated: Boolean read GetTerminated write SetTerminated;
end;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSThread
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCNTSThread - class declaration
===============================================================================}
type
TCNTSThread = class(TThread)
protected
fTaskObject: TCNTSTask;
procedure Execute; override;
public
constructor Create(TaskObject: TCNTSTask);
end;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSManager
--------------------------------------------------------------------------------
===============================================================================}
type
TCNTSTaskState = (
tsReady, // never ran, can be automatically started, initial state
tsInactive, // never ran, paused by user, cannot be automatically started
tsRunning, // running
tsPaused, // running, paused by user
tsQueued, // running, paused by manager, can be automatically unpaused
tsStopping, // running, task was stopped by the user
tsTerminating, // running, manager is waiting for the thread to end
tsCompleted, // completed, returned true
tsAborted); // completed, returned false
TCNTSTaskItem = record
TaskID: TCNTSTaskID;
TaskObject: TCNTSTask;
TaskState: TCNTSTaskState;
TaskStage: Integer;
TaskProgress: Double;
end;
TCNTSTaskItemFull = record
PublicPart: TCNTSTaskItem;
CommEndpoint: TMessangerEndpoint;
CommEndpointID: TMsgrEndpointID;
PauseEvent: TEvent;
AssignedThread: TCNTSThread;
end;
TCNTSTaskEvent = procedure(Sender: TObject; TaskIndex: Integer) of object;
TCNTSTaskCallback = procedure(Sender: TObject; TaskIndex: Integer);
// task index points to a sender
TCNTSMessageEvent = procedure(Sender: TObject; TaskIndex: Integer; var Msg: TCNTSMessage) of object;
TCNTSMessageCallback = procedure(Sender: TObject; TaskIndex: Integer; var Msg: TCNTSMessage);
{===============================================================================
TCNTSManager - class declaration
===============================================================================}
type
TCNTSManager = class(TCustomListObject)
protected
fTasks: array of TCNTSTaskItemFull;
fTaskCount: Integer;
fOwnsTaskObjects: Boolean;
fMaxConcurrentTasks: Integer;
fMessanger: TMessanger;
fCommEndpoint: TMessangerEndpoint;
// events
fOnTaskStateEvent: TCNTSTaskEvent;
fOnTaskStateCallback: TCNTSTaskCallback;
fOnTaskStageProgressEvent: TCNTSTaskEvent;
fOnTaskStageProgressCallback: TCNTSTaskCallback;
fOnTaskProgressEvent: TCNTSTaskEvent;
fOnTaskProgressCallback: TCNTSTaskCallback;
fOnTaskCompleteEvent: TCNTSTaskEvent;
fOnTaskCompleteCallback: TCNTSTaskCallback;
fOnTaskRemovingEvent: TCNTSTaskEvent;
fOnTaskRemovingCallback: TCNTSTaskCallback;
fOnMessageEvent: TCNTSMessageEvent;
fOnMessageCallback: TCNTSMessageCallback;
fOnChangeEvent: TNotifyEvent;
fOnChangeCallback: TNotifyCallback;
// getters, setters
Function GetTask(Index: Integer): TCNTSTaskItem; virtual;
procedure SetMaxConcurrentTasks(Value: Integer); virtual;
// list methods
Function GetCapacity: Integer; override;
procedure SetCapacity(Value: Integer); override;
Function GetCount: Integer; override;
procedure SetCount(Value: Integer); override;
// events firing
procedure DoTaskState(TaskIndex: Integer); virtual;
procedure DoTaskStageProgress(TaskIndex: Integer); virtual;
procedure DoTaskProgress(TaskIndex: Integer); virtual;
procedure DoTaskComplete(TaskIndex: Integer); virtual;
procedure DoTaskRemoving(TaskIndex: Integer); virtual;
procedure DoMessage(TaskIndex: Integer; var Msg: TCNTSMessage); virtual;
procedure DoChange; virtual;
// internal processing methods
Function FindCommEndpoint(CommIndpointID: TMsgrEndpointID; out TaskIndex: Integer): Boolean; virtual;
procedure MessageHandler(Sender: TObject; Msg: TMsgrMessageIn; var Flags: TMsgrDispatchFlags); virtual;
procedure ManageRunningTasks(IgnoredTask: Integer = -1); virtual;
procedure TerminateTask(TaskIndex: Integer); virtual;
procedure WaitAndFreeTask(TaskIndex: Integer); virtual;
procedure ManagedStartTask(TaskIndex: Integer); virtual;
procedure ManagedStopTask(TaskIndex: Integer); virtual;
Function InternalExtractTask(TaskIndex: Integer): TCNTSTask; virtual;
// init, final
procedure Initialize(OwnsTaskObjects: Boolean); virtual;
procedure Finalize; virtual;
public
class Function ProcessorCount: Integer; virtual;
constructor Create(OwnsTaskObjects: Boolean = True);
destructor Destroy; override;
Function LowIndex: Integer; override;
Function HighIndex: Integer; override;
Function First: TCNTSTaskItem; virtual;
Function Last: TCNTSTaskItem; virtual;
// list management
Function IndexOfTask(TaskID: TCNTSTaskID): Integer; overload; virtual;
Function IndexOfTask(TaskObject: TCNTSTask): Integer; overload; virtual;
Function FindTask(TaskID: TCNTSTaskID; out TaskIndex: Integer): Boolean; overload; virtual;
Function FindTask(TaskObject: TCNTSTask; out TaskIndex: Integer): Boolean; overload; virtual;
Function AddTask(TaskID: TCNTSTaskID; TaskObject: TCNTSTask; Active: Boolean = True): Integer; overload; virtual;
Function AddTask(TaskObject: TCNTSTask; Active: Boolean = True): Integer; overload; virtual;
procedure InsertTask(Index: Integer; TaskID: TCNTSTaskID; TaskObject: TCNTSTask; Active: Boolean = True); overload; virtual;
procedure InsertTask(Index: Integer; TaskObject: TCNTSTask; Active: Boolean = True); overload; virtual;
procedure MoveTask(SrcIdx,DstIdx: Integer); virtual;
procedure ExchangeTask(Index1,Index2: Integer); virtual;
Function ExtractTask(TaskID: TCNTSTaskID): TCNTSTask; overload; virtual;
Function ExtractTask(TaskObject: TCNTSTask): TCNTSTask; overload; virtual;
Function RemoveTask(TaskID: TCNTSTaskID): Integer; overload; virtual;
Function RemoveTask(TaskObject: TCNTSTask): Integer; overload; virtual;
procedure DeleteTask(TaskIndex: Integer); virtual;
procedure ClearTasks; virtual;
procedure ClearCompletedTasks; virtual;
// task running management
procedure StartTask(TaskIndex: Integer); virtual;
procedure PauseTask(TaskIndex: Integer); virtual;
procedure ResumeTask(TaskIndex: Integer); virtual;
procedure StopTask(TaskIndex: Integer); virtual;
// task properties
Function GetTaskThreadPriority(TaskIndex: Integer): TThreadPriority; virtual;
Function SetTaskThreadPriority(TaskIndex: Integer; NewPriority: TThreadPriority): TThreadPriority; virtual;
// other task methods
Function RunningTasksCount: Integer; virtual;
procedure RunningTasksWaitFor; virtual;
Function UnfinishedTasksCount(CountPaused: Boolean = True): Integer; virtual;
// messaging
Function PostMessage(TaskIndex: Integer; Param1,Param2: TCNTSMessageParam): Boolean; virtual;
Function SendMessage(TaskIndex: Integer; Param1,Param2: TCNTSMessageParam): TCNTSMessageResult; virtual;
procedure Update(Timeout: UInt32 = 0); virtual;
// properties
property Tasks[Index: Integer]: TCNTSTaskItem read GetTask; default;
property TaskCount: Integer read GetCount;
property OwnsTaskObjects: Boolean read fOwnsTaskObjects write fOwnsTaskObjects;
property MaxConcurrentTasks: Integer read fMaxConcurrentTasks write SetMaxConcurrentTasks;
// events
property OnTaskStateCallback: TCNTSTaskCallback read fOnTaskStateCallback write fOnTaskStateCallback;
property OnTaskStateEvent: TCNTSTaskEvent read fOnTaskStateEvent write fOnTaskStateEvent;
property OnTaskState: TCNTSTaskEvent read fOnTaskStateEvent write fOnTaskStateEvent;
property OnTaskStageProgressCallback: TCNTSTaskCallback read fOnTaskProgressCallback write fOnTaskProgressCallback;
property OnTaskStageProgressEvent: TCNTSTaskEvent read fOnTaskProgressEvent write fOnTaskProgressEvent;
property OnTaskStageProgress: TCNTSTaskEvent read fOnTaskProgressEvent write fOnTaskProgressEvent;
property OnTaskProgressEventCallback: TCNTSTaskCallback read fOnTaskProgressCallback write fOnTaskProgressCallback;
property OnTaskProgressEvent: TCNTSTaskEvent read fOnTaskProgressEvent write fOnTaskProgressEvent;
property OnTaskProgress: TCNTSTaskEvent read fOnTaskProgressEvent write fOnTaskProgressEvent;
property OnTaskCompleteCallback: TCNTSTaskCallback read fOnTaskCompleteCallback write fOnTaskCompleteCallback;
property OnTaskCompleteEvent: TCNTSTaskEvent read fOnTaskCompleteEvent write fOnTaskCompleteEvent;
property OnTaskComplete: TCNTSTaskEvent read fOnTaskCompleteEvent write fOnTaskCompleteEvent;
property OnTaskRemovingCallback: TCNTSTaskCallback read fOnTaskRemovingCallback write fOnTaskRemovingCallback;
property OnTaskRemovingEvent: TCNTSTaskEvent read fOnTaskRemovingEvent write fOnTaskRemovingEvent;
property OnTaskRemoving: TCNTSTaskEvent read fOnTaskRemovingEvent write fOnTaskRemovingEvent;
property OnMessageCallback: TCNTSMessageCallback read fOnMessageCallback write fOnMessageCallback;
property OnMessageEvent: TCNTSMessageEvent read fOnMessageEvent write fOnMessageEvent;
property OnMessage: TCNTSMessageEvent read fOnMessageEvent write fOnMessageEvent;
property OnChangeCallback: TNotifyCallback read fOnChangeCallback write fOnChangeCallback;
property OnChangeEvent: TNotifyEvent read fOnChangeEvent write fOnChangeEvent;
property OnChange: TNotifyEvent read fOnChangeEvent write fOnChangeEvent;
end;
implementation
uses
{$IFDEF Windows}Windows,{$ELSE}BaseUnix,{$ENDIF}
InterlockedOps;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W4055:={$WARN 4055 OFF}} // Conversion between ordinals and pointers is not portable
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
External functions
===============================================================================}
{$IFDEF Windows}
procedure GetNativeSystemInfo(lpSystemInfo: PSystemInfo); stdcall; external kernel32;
{$ELSE}
const
//_SC_NPROCESSORS_CONF = 83; // not used anywhere
_SC_NPROCESSORS_ONLN = 84;
Function sysconf(name: cInt): cLong; cdecl; external;
{$ENDIF}
{===============================================================================
--------------------------------------------------------------------------------
TCNTSTask
--------------------------------------------------------------------------------
===============================================================================}
const
CNTS_MSGR_ENDPOINT_MANAGER = 0;
CNTS_MSG_USER = 0;
CNTS_MSG_TERMINATE = 1;
CNTS_MSG_PROGRESS = 2;
CNTS_MSG_STAGEPROGRESS = 3;
CNTS_MSG_COMPLETED = 100;
{===============================================================================
TCNTSTask - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TCNTSTask - protected methods
-------------------------------------------------------------------------------}
Function TCNTSTask.GetTerminated: Boolean;
begin
Result := InterlockedLoad(fTerminated) <> 0;
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.SetTerminated(Value: Boolean);
begin
If Value then
InterlockedStore(fTerminated,-1)
else
InterlockedStore(fTerminated,0);
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W4055 W5024{$ENDIF}
procedure TCNTSTask.InternalMessageHandler(Sender: TObject; Msg: TMsgrMessageIn; var Flags: TMsgrDispatchFlags);
var
TempMessage: TCNTSMessage;
begin
case Msg.Parameter1 of
CNTS_MSG_USER:
begin
TempMessage.Param1 := Msg.Parameter2;
TempMessage.Param2 := Msg.Parameter3;
TempMessage.Result := 0;
ProcessMessage(TempMessage);
If mdfSentMessage in Flags then
TCNTSMessageResult(Pointer(Msg.Parameter4)^) := TempMessage.Result;
end;
CNTS_MSG_TERMINATE:
Terminate;
end;
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
procedure TCNTSTask.InternalSetup(TaskID: TCNTSTaskID; CommEndpoint: TMessangerEndpoint; PauseEvent: TEvent);
begin
fTaskID := TaskID;
fCommEndpoint := CommEndpoint;
fCommEndpoint.OnMessageEvent := InternalMessageHandler;
fPauseEvent := PauseEvent;
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.InternalExecute;
var
MainProcResult: Integer;
begin
Cycle(0); // process all messages received to this point
If Main then // main processing
MainProcResult := -1
else
MainProcResult := 0;
fCommEndpoint.PostMessage(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_COMPLETED,TMsgrParam(MainProcResult),0,0);
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.ProcessMessage(var Msg: TCNTSMessage);
begin
Msg.Result := 0;
end;
{-------------------------------------------------------------------------------
TCNTSTask - public methods
-------------------------------------------------------------------------------}
procedure TCNTSTask.Terminate;
begin
InterlockedStore(fTerminated,-1);
end;
//------------------------------------------------------------------------------
Function TCNTSTask.PostMessage(Param1,Param2: TCNTSMessageParam): Boolean;
begin
Result := fCommEndpoint.PostMessage(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_USER,Param1,Param2,0);
end;
//------------------------------------------------------------------------------
Function TCNTSTask.SendMessage(Param1,Param2: TCNTSMessageParam): TCNTSMessageResult;
begin
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
If not fCommEndpoint.SendMessage(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_USER,Param1,Param2,TMsgrParam(Addr(Result))) then
Result := 0;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.SignalStageProgress(Stage: Integer; Progress: Double);
var
ValueLo: TCNTSMessageParam;
ValueHi: TCNTSMessageParam;
begin
ValueLo := TCNTSMessageParam(UInt32(Addr(Progress)^));
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
ValueHi := TCNTSMessageParam(PUInt32(PtrUInt(Addr(Progress)) + SizeOf(UInt32))^);
{$IFDEF FPCDWM}{$POP}{$ENDIF}
fCommEndpoint.PostMessage(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_STAGEPROGRESS,ValueLo,ValueHi,TCNTSMessageParam(Stage));
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.SignalProgress(Progress: Double);
var
ValueLo: TCNTSMessageParam;
ValueHi: TCNTSMessageParam;
begin
ValueLo := TCNTSMessageParam(UInt32(Addr(Progress)^));
{$IFDEF FPCDWM}{$PUSH}W4055{$ENDIF}
ValueHi := TCNTSMessageParam(PUInt32(PtrUInt(Addr(Progress)) + SizeOf(UInt32))^);
{$IFDEF FPCDWM}{$POP}{$ENDIF}
fCommEndpoint.PostMessage(CNTS_MSGR_ENDPOINT_MANAGER,CNTS_MSG_PROGRESS,ValueLo,ValueHi,0);
end;
//------------------------------------------------------------------------------
procedure TCNTSTask.Cycle(Timeout: UInt32 = 0);
begin
fCommEndpoint.Cycle(Timeout);
fPauseEvent.Wait(INFINITE);
end;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSThread
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCNTSThread - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TCNTSThread - protected methods
-------------------------------------------------------------------------------}
procedure TCNTSThread.Execute;
begin
fTaskObject.InternalExecute;
end;
{-------------------------------------------------------------------------------
TCNTSThread - public methods
-------------------------------------------------------------------------------}
constructor TCNTSThread.Create(TaskObject: TCNTSTask);
begin
inherited Create(False);
Priority := tpLower;
FreeOnTerminate := False;
fTaskObject := TaskObject;
end;
{===============================================================================
--------------------------------------------------------------------------------
TCNTSManager
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TCNTSManager - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TCNTSManager - protected methods
-------------------------------------------------------------------------------}
Function TCNTSManager.GetTask(Index: Integer): TCNTSTaskItem;
begin
If CheckIndex(Index) then
Result := fTasks[Index].PublicPart
else
raise ECNSTIndexOutOfBounds.CreateFmt('TCNTSManager.GetTask: Index (%d) out of bounds.',[Index]);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.SetMaxConcurrentTasks(Value: Integer);
begin
If Value >= 1 then
begin
fMaxConcurrentTasks := Value;
ManageRunningTasks;
end
else raise ECNTSInvalidValue.CreateFmt('TCNTSManager.SetMaxConcurrentTasks: Cannot assign value smaller than 1 (%d).',[Value]);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.GetCapacity: Integer;
begin
Result := Length(fTasks);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.SetCapacity(Value: Integer);
begin
SetLength(fTasks,Value);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.GetCount: Integer;
begin
Result := fTaskCount;
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W5024{$ENDIF}
procedure TCNTSManager.SetCount(Value: Integer);
begin
// do nothing
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
procedure TCNTSManager.DoTaskState(TaskIndex: Integer);
begin
If Assigned(fOnTaskStateEvent) then
fOnTaskStateEvent(Self,TaskIndex)
else If Assigned(fOnTaskStateCallback) then
fOnTaskStateCallback(Self,TaskIndex);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.DoTaskStageProgress(TaskIndex: Integer);
begin
If Assigned(fOnTaskStageProgressEvent) then
fOnTaskStageProgressEvent(Self,TaskIndex)
else If Assigned(fOnTaskStageProgressCallback) then
fOnTaskStageProgressCallback(Self,TaskIndex);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.DoTaskProgress(TaskIndex: Integer);
begin
If Assigned(fOnTaskProgressEvent) then
fOnTaskProgressEvent(Self,TaskIndex)
else If Assigned(fOnTaskProgressCallback) then
fOnTaskProgressCallback(Self,TaskIndex);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.DoTaskComplete(TaskIndex: Integer);
begin
If Assigned(fOnTaskCompleteEvent) then
fOnTaskCompleteEvent(Self,TaskIndex)
else If Assigned(fOnTaskCompleteCallback) then
fOnTaskCompleteCallback(Self,TaskIndex);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.DoTaskRemoving(TaskIndex: Integer);
begin
If Assigned(fOnTaskRemovingEvent) then
fOnTaskRemovingEvent(Self,TaskIndex)
else If Assigned(fOnTaskRemovingCallback) then
fOnTaskRemovingCallback(Self,TaskIndex);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.DoMessage(TaskIndex: Integer; var Msg: TCNTSMessage);
begin
If Assigned(fOnMessageEvent) then
fOnMessageEvent(Self,TaskIndex,Msg)
else If Assigned(fOnMessageCallback) then
fOnMessageCallback(Self,TaskIndex,Msg);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.DoChange;
begin
If Assigned(fOnChangeEvent) then
fOnChangeEvent(Self)
else If Assigned(fOnChangeCallback) then
fOnChangeCallback(Self);
end;
//------------------------------------------------------------------------------
Function TCNTSManager.FindCommEndpoint(CommIndpointID: TMsgrEndpointID; out TaskIndex: Integer): Boolean;
var
i: Integer;
begin
Result := False;
TaskIndex := -1;
For i := LowIndex to HighIndex do
If Assigned(fTasks[i].CommEndpoint) then
If fTasks[i].CommEndpoint.EndpointID = CommIndpointID then
begin
TaskIndex := i;
Result := True;
Break{For i};
end;
end;
//------------------------------------------------------------------------------
{$IFDEF FPCDWM}{$PUSH}W4055 W5024{$ENDIF}
procedure TCNTSManager.MessageHandler(Sender: TObject; Msg: TMsgrMessageIn; var Flags: TMsgrDispatchFlags);
var
TempMessage: TCNTSMessage;
TaskIndex: Integer;
PrgsBuffer: Int64;
begin
case Msg.Parameter1 of
CNTS_MSG_USER:
If FindCommEndpoint(Msg.Sender,TaskIndex) then
begin
TempMessage.Param1 := Msg.Parameter2;
TempMessage.Param2 := Msg.Parameter3;
TempMessage.Result := 0;
DoMessage(TaskIndex,TempMessage);
If mdfSentMessage in Flags then
TCNTSMessageResult(Pointer(Msg.Parameter4)^) := TempMessage.Result;
end;
CNTS_MSG_STAGEPROGRESS:
If FindCommEndpoint(Msg.Sender,TaskIndex) then
begin
Int64Rec(PrgsBuffer).Lo := UInt32(Msg.Parameter2);
Int64Rec(PrgsBuffer).Hi := UInt32(Msg.Parameter3);
fTasks[TaskIndex].PublicPart.TaskProgress := Double(Addr(PrgsBuffer)^);
fTasks[TaskIndex].PublicPart.TaskStage := Integer(Msg.Parameter4);
DoTaskStageProgress(TaskIndex);
end;
CNTS_MSG_PROGRESS:
If FindCommEndpoint(Msg.Sender,TaskIndex) then
begin
Int64Rec(PrgsBuffer).Lo := UInt32(Msg.Parameter2);
Int64Rec(PrgsBuffer).Hi := UInt32(Msg.Parameter3);
fTasks[TaskIndex].PublicPart.TaskProgress := Double(Addr(PrgsBuffer)^);
DoTaskProgress(TaskIndex);
end;
CNTS_MSG_COMPLETED:
begin
If FindCommEndpoint(Msg.Sender,TaskIndex) then
begin
If Assigned(fTasks[TaskIndex].AssignedThread) then
fTasks[TaskIndex].AssignedThread.WaitFor;
If Msg.Parameter2 <> 0 then
fTasks[TaskIndex].PublicPart.TaskState := tsCompleted
else
fTasks[TaskIndex].PublicPart.TaskState := tsAborted;
DoTaskState(TaskIndex);
DoTaskComplete(TaskIndex);
ManageRunningTasks;
end
else ManageRunningTasks;
end;
end;
end;
{$IFDEF FPCDWM}{$POP}{$ENDIF}
//------------------------------------------------------------------------------
procedure TCNTSManager.ManageRunningTasks(IgnoredTask: Integer = -1);
var
RunCount: Integer;
i: Integer;
begin
RunCount := fMaxConcurrentTasks - RunningTasksCount;
If RunCount > 0 then
begin
For i := LowIndex to HighIndex do
If RunCount > 0 then
begin
If (fTasks[i].PublicPart.TaskState in [tsReady,tsQueued]) and (i <> IgnoredTask) then
begin
ManagedStartTask(i);
Dec(RunCount);
end;
end
else Break{For i};
end
else If RunCount < 0 then
begin
For i := HighIndex downto LowIndex do
If RunCount < 0 then
begin
If (fTasks[i].PublicPart.TaskState = tsRunning) and (i <> IgnoredTask) then
begin
ManagedStopTask(i);
Inc(RunCount);
end;
end
else Break{For i};
end;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.TerminateTask(TaskIndex: Integer);
begin
case fTasks[TaskIndex].PublicPart.TaskState of
tsReady,
tsInactive:
fTasks[TaskIndex].PublicPart.TaskState := tsAborted;
tsRunning:
begin
fCommEndpoint.PostMessage(fTasks[TaskIndex].CommEndpointID,CNTS_MSG_TERMINATE,0,0,0,MSGR_PRIORITY_ABSOLUTE);
fTasks[TaskIndex].PublicPart.TaskState := tsTerminating;
end;
tsPaused,
tsQueued:
begin
fCommEndpoint.PostMessage(fTasks[TaskIndex].CommEndpointID,CNTS_MSG_TERMINATE,0,0,0,MSGR_PRIORITY_ABSOLUTE);
fTasks[TaskIndex].PauseEvent.Unlock;
fTasks[TaskIndex].PublicPart.TaskState := tsTerminating;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.WaitAndFreeTask(TaskIndex: Integer);
begin
If Assigned(fTasks[TaskIndex].AssignedThread) then
begin
// wait for task to truly exit
fTasks[TaskIndex].AssignedThread.WaitFor;
fTasks[TaskIndex].AssignedThread.Free;
end;
fTasks[TaskIndex].CommEndpoint.Free;
fTasks[TaskIndex].PauseEvent.Free;
If fOwnsTaskObjects then
fTasks[TaskIndex].PublicPart.TaskObject.Free
else
DoTaskRemoving(TaskIndex);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.ManagedStartTask(TaskIndex: Integer);
begin
case fTasks[TaskIndex].PublicPart.TaskState of
tsReady: begin
fTasks[TaskIndex].PublicPart.TaskObject.InternalSetup(
fTasks[TaskIndex].PublicPart.TaskID,
fTasks[TaskIndex].CommEndpoint,
fTasks[TaskIndex].PauseEvent);
fTasks[TaskIndex].AssignedThread := TCNTSThread.Create(fTasks[TaskIndex].PublicPart.TaskObject);
fTasks[TaskIndex].PublicPart.TaskState := tsRunning;
DoTaskState(TaskIndex);
end;
tsQueued: begin
fTasks[TaskIndex].PauseEvent.Unlock;
fTasks[TaskIndex].PublicPart.TaskState := tsRunning;
DoTaskState(TaskIndex);
end;
end;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.ManagedStopTask(TaskIndex: Integer);
begin
If fTasks[TaskIndex].PublicPart.TaskState = tsRunning then
begin
fTasks[TaskIndex].PauseEvent.Lock;
fTasks[TaskIndex].PublicPart.TaskState := tsQueued;
DoTaskState(TaskIndex);
end;
end;
//------------------------------------------------------------------------------
Function TCNTSManager.InternalExtractTask(TaskIndex: Integer): TCNTSTask;
var
i: Integer;
begin
If fTasks[TaskIndex].PublicPart.TaskState in [tsReady,tsInactive,tsCompleted,tsAborted] then
begin
If Assigned(fTasks[TaskIndex].AssignedThread) then
begin
fTasks[TaskIndex].AssignedThread.WaitFor;
fTasks[TaskIndex].AssignedThread.Free;
end;
fTasks[TaskIndex].CommEndpoint.Free;
fTasks[TaskIndex].PauseEvent.Free;
Result := fTasks[TaskIndex].PublicPart.TaskObject;
For i := TaskIndex to Pred(HighIndex) do
fTasks[i] := fTasks[i + 1];
Dec(fTaskCount);
Shrink;
DoChange;
end
else raise ECNTSTaskRunning.CreateFmt('TCNTSManager.InternalExtractTask: Cannot extract running task (#%d).',[TaskIndex]);
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.Initialize(OwnsTaskObjects: Boolean);
begin
SetLength(fTasks,0);
fTaskCount := 0;
fOwnsTaskObjects := OwnsTaskObjects;
fMaxConcurrentTasks := ProcessorCount;
fMessanger := TMessanger.Create(1024);
fCommEndpoint := fMessanger.CreateEndpoint(CNTS_MSGR_ENDPOINT_MANAGER);
fCommEndpoint.OnMessage := MessageHandler;
// init events
fOnTaskStateEvent := nil;
fOnTaskStateCallback := nil;
fOnTaskStageProgressEvent := nil;
fOnTaskStageProgressCallback := nil;
fOnTaskProgressEvent := nil;
fOnTaskProgressCallback := nil;
fOnTaskCompleteEvent := nil;
fOnTaskCompleteCallback := nil;
fOnTaskRemovingEvent := nil;
fOnTaskRemovingCallback := nil;
fOnMessageEvent := nil;
fOnMessageCallback := nil;
fOnChangeEvent := nil;
fOnChangeCallback := nil;
end;
//------------------------------------------------------------------------------
procedure TCNTSManager.Finalize;
begin
// prevent events firing (except for task removal)
fOnTaskStateEvent := nil;
fOnTaskStateCallback := nil;
fOnTaskStageProgressEvent := nil;
fOnTaskStageProgressCallback := nil;
fOnTaskProgressEvent := nil;
fOnTaskProgressCallback := nil;
fOnTaskCompleteEvent := nil;
fOnTaskCompleteCallback := nil;
fOnMessageEvent := nil;
fOnMessageCallback := nil;
fOnChangeEvent := nil;
fOnChangeCallback := nil;
// clear
ClearTasks;
fCommEndpoint.Free;
fMessanger.Free;
end;
{-------------------------------------------------------------------------------
TCNTSManager - public methods
-------------------------------------------------------------------------------}
class Function TCNTSManager.ProcessorCount: Integer;
{$IFDEF Windows}
var