-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTasks.pas
More file actions
executable file
·1307 lines (1175 loc) · 39.7 KB
/
Copy pathTasks.pas
File metadata and controls
executable file
·1307 lines (1175 loc) · 39.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
unit Tasks;
{
г======================================================================¬
¦ Tasks.pas v2 — Task Parallel Library for Delphi 7 ¦
¦======================================================================¦
¦ NEW in v2: ¦
¦ • TCancellationToken — cooperative cancellation flag ¦
¦ • TCancellationTokenSource — manages the token ¦
¦ • TTaskCancelProc/Method — callbacks that receive the token ¦
¦ • ETaskCancelled — transitions task to tsCancelled (not tsFailed) ¦
¦ • ITask.Cancel — manual cancellation ¦
¦ • ITask.CancelAfter(ms) — timeout cancellation ¦
¦======================================================================¦
¦ COOPERATIVE CANCELLATION PRINCIPLE ¦
¦ ¦
¦ Windows threads cannot be forcibly stopped without risk ¦
¦ of data corruption. Therefore: ¦
¦ ¦
¦ • Primitive tasks (TTaskProc) — Cancel only prevents ¦
¦ start (if the task is still in the queue) ¦
¦ ¦
¦ • Tasks with TTaskCancelProc — receive a token and MUST ¦
¦ periodically call AToken.ThrowIfCancellationRequested (or check ¦
¦ AToken.IsCancellationRequested) ¦
L======================================================================-
}
interface
uses
Windows, SysUtils, Classes;
type
{ ------------------------------------------------------------------ }
{ Continuation options }
{ ------------------------------------------------------------------ }
TContinuationOption = (
coAlways, // always (default)
coOnlyOnSuccess, // only on tsCompleted
coOnlyOnFailed, // only on tsFailed
coOnMainThread // on main thread (Synchronize)
);
TContinuationOptions = set of TContinuationOption;
const
TASK_POOL_SIZE_AUTO = 0;
TASK_PUMP_INTERVAL = 15; // ms: CheckSynchronize interval during Wait
coDefault : TContinuationOptions = [coAlways];
coSuccessOnly : TContinuationOptions = [coOnlyOnSuccess];
coFailedOnly : TContinuationOptions = [coOnlyOnFailed];
coMainAlways : TContinuationOptions = [coAlways, coOnMainThread];
coMainOnSuccess : TContinuationOptions = [coOnlyOnSuccess, coOnMainThread];
coMainOnFailed : TContinuationOptions = [coOnlyOnFailed, coOnMainThread];
type
{ ------------------------------------------------------------------ }
{ Forward }
{ ------------------------------------------------------------------ }
TCancellationToken = class;
{ ------------------------------------------------------------------ }
{ Cooperative cancellation exception }
{ Throw via AToken.ThrowIfCancellationRequested }
{ The task will catch it and go to tsCancelled (not tsFailed) }
{ ------------------------------------------------------------------ }
ETaskCancelled = class(Exception)
public
constructor Create;
end;
{ ------------------------------------------------------------------ }
{ Task state }
{ ------------------------------------------------------------------ }
TTaskState = (
tsPending, // waiting in the pool queue
tsRunning, // executing
tsCompleted, // completed successfully
tsFailed, // completed with an exception
tsCancelled // cancelled (before start or during execution)
);
{ ------------------------------------------------------------------ }
{ Callback types }
{ ------------------------------------------------------------------ }
{ Standard (no internal cancellation support) }
TTaskProc = procedure(AData: Pointer);
TTaskMethod = procedure(AData: Pointer) of object;
{ Cooperative cancellation: token is passed inside }
TTaskCancelProc = procedure(AData: Pointer; AToken: TCancellationToken);
TTaskCancelMethod = procedure(AData: Pointer; AToken: TCancellationToken) of object;
{ ------------------------------------------------------------------ }
{ ITask }
{ ------------------------------------------------------------------ }
ITask = interface
['{9A3F7B2E-4C51-4D8A-B6E3-12F09A8B4C7D}']
procedure Wait;
function ContinueWith(AProc : TTaskProc;
AData : Pointer;
AOptions: TContinuationOptions): ITask; overload;
function ContinueWith(AMethod: TTaskMethod;
AData : Pointer;
AOptions: TContinuationOptions): ITask; overload;
{ --- Cancellation --- }
procedure Cancel;
procedure CancelAfter(ATimeoutMs: Cardinal);
{ --- WinAPI event for WaitAll/WaitAny --- }
function GetWaitHandle: THandle;
{ --- State --- }
function GetState : TTaskState;
function GetErrorMessage: string;
function GetIsCompleted : Boolean;
function GetIsSuccess : Boolean;
function GetIsFailed : Boolean;
function GetIsCancelled : Boolean;
property State : TTaskState read GetState;
property ErrorMessage : string read GetErrorMessage;
property IsCompleted : Boolean read GetIsCompleted;
property IsSuccess : Boolean read GetIsSuccess;
property IsFailed : Boolean read GetIsFailed;
property IsCancelled : Boolean read GetIsCancelled;
property WaitHandle : THandle read GetWaitHandle;
end;
TThreadPool = class; // forward
{ ================================================================== }
{ TCancellationToken }
{ Thread-safe cancellation flag with optional auto-timer }
{ ================================================================== }
TCancellationToken = class
private
FCancelled : LongBool; // read/written via Interlocked
FTimerThread : TObject; // TCancelTimerThread (forward-compat)
FCS : TRTLCriticalSection; // protects FTimerThread
public
constructor Create;
destructor Destroy; override;
{ Was cancellation requested? }
function IsCancellationRequested: Boolean;
{ Throws ETaskCancelled if cancellation was requested }
procedure ThrowIfCancellationRequested;
{ Immediate cancellation }
procedure Cancel;
{ Cancellation after ATimeoutMs milliseconds (replaces previous timer) }
procedure CancelAfter(ATimeoutMs: Cardinal);
{ Singleton "never cancelled" — do not free! }
class function None: TCancellationToken;
end;
{ ================================================================== }
{ TCancellationTokenSource }
{ C#-style: Source manages, Token observes }
{ }
{ Source := TCancellationTokenSource.Create; }
{ Source.CancelAfter(3000); }
{ T := TTask.Run(@MyProc, Data, Source.Token); }
{ ... }
{ Source.Free; // only after T.Wait ! }
{ ================================================================== }
TCancellationTokenSource = class
private
FToken: TCancellationToken; // owns it
public
constructor Create;
constructor CreateWithTimeout(ATimeoutMs: Cardinal);
destructor Destroy; override;
procedure Cancel;
procedure CancelAfter(ATimeoutMs: Cardinal);
function GetToken: TCancellationToken;
function GetIsCancellationRequested: Boolean;
property Token : TCancellationToken read GetToken;
property IsCancellationRequested: Boolean read GetIsCancellationRequested;
end;
TTask = class;
TTasksArray=array of TTask;
{ ================================================================== }
{ TTask }
{ ================================================================== }
TTask = class(TInterfacedObject, ITask)
private
{ --- Callbacks --- }
FProc : TTaskProc;
FMethod : TTaskMethod;
FCancelProc : TTaskCancelProc; // NEW
FCancelMethod : TTaskCancelMethod; // NEW
FData : Pointer;
FPool : TThreadPool;
{ --- State --- }
FState : TTaskState;
FErrorMsg : string;
{ --- Synchronization --- }
FDoneEvent : THandle;
FCS : TRTLCriticalSection;
{ --- Continuations --- }
FConts : TTasksArray;
FContOpts : array of TContinuationOptions;
FContCount : Integer;
{ --- Cancellation --- }
FToken : TCancellationToken; // NEW: weak reference (sometimes owned)
FOwnsToken : Boolean; // NEW: True -> free in Destroy
FCancelFlag : LongBool; // NEW: set via Cancel()
{ --- Marshalling to UI --- }
FRunOnMain : Boolean;
private
procedure InitFields(AData: Pointer; APool: TThreadPool);
function AddContinuation(ACont: TTask; AOptions: TContinuationOptions): ITask;
function IsExternalCancellationRequested: Boolean; // NEW
procedure InternalExecute;
procedure Complete(const AErrMsg: string);
procedure CancelSelf;
procedure ScheduleContinuations;
function ShouldRunCont(AOptions: TContinuationOptions;
AParentState: TTaskState): Boolean;
{ ITask }
function GetState : TTaskState;
function GetErrorMessage: string;
function GetIsCompleted : Boolean;
function GetIsSuccess : Boolean;
function GetIsFailed : Boolean;
function GetIsCancelled : Boolean;
function GetWaitHandle : THandle;
public
{ --- Constructors (standard) --- }
constructor Create(AProc : TTaskProc;
AData : Pointer; APool: TThreadPool); overload;
constructor Create(AMethod: TTaskMethod;
AData : Pointer; APool: TThreadPool); overload;
{ --- Constructors: standard callback + external token ---------- }
{ Token is NOT passed to the callback, but affects start/timeout }
constructor Create(AProc : TTaskProc; AData: Pointer;
AToken : TCancellationToken;
APool : TThreadPool); overload;
constructor Create(AMethod: TTaskMethod; AData: Pointer;
AToken : TCancellationToken;
APool : TThreadPool); overload;
{ --- Constructors: cancel-aware callback + token ----------------- }
{ AOwnsToken=True -> TTask will free the token when destroyed }
constructor Create(ACancelProc : TTaskCancelProc; AData: Pointer;
AToken : TCancellationToken;
AOwnsToken : Boolean;
APool : TThreadPool); overload;
constructor Create(ACancelMethod: TTaskCancelMethod; AData: Pointer;
AToken : TCancellationToken;
AOwnsToken : Boolean;
APool : TThreadPool); overload;
destructor Destroy; override;
{ ITask }
procedure Wait;
function ContinueWith(AProc : TTaskProc;
AData : Pointer;
AOptions: TContinuationOptions): ITask; overload;
function ContinueWith(AMethod: TTaskMethod;
AData : Pointer;
AOptions: TContinuationOptions): ITask; overload;
procedure Cancel;
procedure CancelAfter(ATimeoutMs: Cardinal);
property State : TTaskState read GetState;
property ErrorMessage : string read GetErrorMessage;
property IsCompleted : Boolean read GetIsCompleted;
property IsSuccess : Boolean read GetIsSuccess;
property IsFailed : Boolean read GetIsFailed;
property IsCancelled : Boolean read GetIsCancelled;
property WaitHandle : THandle read GetWaitHandle;
{ ——— FACTORY METHODS ——— }
{ Basic }
class function Run(AProc : TTaskProc;
AData : Pointer = nil): ITask; overload;
class function Run(AMethod: TTaskMethod;
AData : Pointer = nil): ITask; overload;
{ With custom pool }
class function Run(AProc : TTaskProc;
AData : Pointer;
APool : TThreadPool): ITask; overload;
class function Run(AMethod: TTaskMethod;
AData : Pointer;
APool : TThreadPool): ITask; overload;
{ Standard callback + external token (only pre-start cancellation) }
class function Run(AProc : TTaskProc;
AData : Pointer;
AToken : TCancellationToken): ITask; overload;
class function Run(AMethod: TTaskMethod;
AData : Pointer;
AToken : TCancellationToken): ITask; overload;
{ Cancel-aware callback + token (full cooperative cancellation) }
class function Run(ACancelProc : TTaskCancelProc;
AData : Pointer;
AToken : TCancellationToken): ITask; overload;
class function Run(ACancelMethod: TTaskCancelMethod;
AData : Pointer;
AToken : TCancellationToken): ITask; overload;
class function Run(ACancelProc : TTaskCancelProc;
AData : Pointer;
AToken : TCancellationToken;
APool : TThreadPool): ITask; overload;
class function Run(ACancelMethod: TTaskCancelMethod;
AData : Pointer;
AToken : TCancellationToken;
APool : TThreadPool): ITask; overload;
{ ——— AGGREGATES ——— }
class procedure WaitAll(const ATasks: array of ITask);
class function WaitAny(const ATasks: array of ITask): Integer;
end;
{ ================================================================== }
{ TTaskQueue — thread-safe queue (circular buffer) }
{ ================================================================== }
TTaskQueue = class
private
FBuf : TTasksArray;
FHead : Integer;
FTail : Integer;
FCapacity : Integer;
FCount : Integer;
FCS : TRTLCriticalSection;
FSem : THandle;
FDone : Boolean;
procedure Grow;
public
constructor Create(ACapacity: Integer = 64);
destructor Destroy; override;
procedure Enqueue(ATask: TTask);
function Dequeue: TTask;
procedure Terminate;
end;
{ ================================================================== }
{ TWorkerThread }
{ ================================================================== }
TWorkerThread = class(TThread)
private
FQueue : TTaskQueue;
FSyncTask : TTask;
procedure DoRunOnMain;
protected
procedure Execute; override;
public
constructor Create(AQueue: TTaskQueue);
end;
{ ================================================================== }
{ TThreadPool }
{ ================================================================== }
TThreadPool = class
private
FQueue : TTaskQueue;
FWorkers : array of TWorkerThread;
FCount : Integer;
public
constructor Create(AWorkerCount: Integer = TASK_POOL_SIZE_AUTO);
destructor Destroy; override;
procedure Enqueue(ATask: TTask);
property WorkerCount: Integer read FCount;
class function Default: TThreadPool;
class procedure ReleaseDefault;
end;
implementation
{ ======================================================
Global state
====================================================== }
var
GMainThreadID : Cardinal;
GDefaultPool : TThreadPool = nil;
GPoolCS : TRTLCriticalSection;
GNoneToken : TCancellationToken = nil; // singleton "never cancelled"
{ ======================================================
Utilities
====================================================== }
function IsMainThread: Boolean;
begin
Result := GetCurrentThreadId = GMainThreadID;
end;
procedure SmartWaitSingle(AEvent: THandle);
begin
if IsMainThread then
while WaitForSingleObject(AEvent, TASK_PUMP_INTERVAL) = WAIT_TIMEOUT do
CheckSynchronize
else
WaitForSingleObject(AEvent, INFINITE);
end;
{ ======================================================
ETaskCancelled
====================================================== }
constructor ETaskCancelled.Create;
begin
inherited Create('Task was cancelled');
end;
{ ======================================================
TCancelTimerThread (internal)
Waits FDelay ms; if not interrupted — cancels the token
====================================================== }
type
TCancelTimerThread = class(TThread)
private
FToken : TCancellationToken;
FDelay : Cardinal;
FAbort : THandle; // early timer abort event
protected
procedure Execute; override;
public
constructor Create(AToken: TCancellationToken; ADelay: Cardinal);
destructor Destroy; override;
procedure AbortTimer;
end;
constructor TCancelTimerThread.Create(AToken: TCancellationToken;
ADelay: Cardinal);
begin
FToken := AToken;
FDelay := ADelay;
FAbort := CreateEvent(nil, False, False, nil);
FreeOnTerminate := False;
inherited Create(False);
end;
destructor TCancelTimerThread.Destroy;
begin
CloseHandle(FAbort);
inherited;
end;
procedure TCancelTimerThread.AbortTimer;
begin
SetEvent(FAbort);
end;
procedure TCancelTimerThread.Execute;
begin
// Wait FDelay ms; if FAbort is signaled earlier — exit quietly
if WaitForSingleObject(FAbort, FDelay) = WAIT_TIMEOUT then
if not Terminated then
FToken.Cancel;
end;
{ ======================================================
TCancellationToken
====================================================== }
constructor TCancellationToken.Create;
begin
inherited Create;
FCancelled := False;
FTimerThread := nil;
InitializeCriticalSection(FCS);
end;
destructor TCancellationToken.Destroy;
var
T: TCancelTimerThread;
begin
// Cancel the timer under lock, wait outside
EnterCriticalSection(FCS);
T := TCancelTimerThread(FTimerThread);
FTimerThread := nil;
LeaveCriticalSection(FCS);
if T <> nil then
begin
T.AbortTimer;
T.WaitFor;
T.Free;
end;
DeleteCriticalSection(FCS);
inherited;
end;
function TCancellationToken.IsCancellationRequested: Boolean;
begin
// LongBool on x86 is guaranteed to be read atomically
Result := FCancelled;
end;
procedure TCancellationToken.ThrowIfCancellationRequested;
begin
if FCancelled then
raise ETaskCancelled.Create;
end;
procedure TCancellationToken.Cancel;
begin
// Interlocked write; no CS needed for a simple flag
InterlockedExchange(Integer(FCancelled), Integer(True));
end;
procedure TCancellationToken.CancelAfter(ATimeoutMs: Cardinal);
var
OldThread: TCancelTimerThread;
NewThread: TCancelTimerThread;
begin
if ATimeoutMs = 0 then
begin
Cancel;
Exit;
end;
// Create new timer; stop the old one
NewThread := TCancelTimerThread.Create(Self, ATimeoutMs);
EnterCriticalSection(FCS);
OldThread := TCancelTimerThread(FTimerThread);
FTimerThread := NewThread;
LeaveCriticalSection(FCS);
if OldThread <> nil then
begin
OldThread.AbortTimer;
OldThread.WaitFor;
OldThread.Free;
end;
end;
class function TCancellationToken.None: TCancellationToken;
begin
// Initialised in the initialization section — thread-safe without CS
Result := GNoneToken;
end;
{ ======================================================
TCancellationTokenSource
====================================================== }
constructor TCancellationTokenSource.Create;
begin
inherited Create;
FToken := TCancellationToken.Create;
end;
constructor TCancellationTokenSource.CreateWithTimeout(ATimeoutMs: Cardinal);
begin
Create;
CancelAfter(ATimeoutMs);
end;
destructor TCancellationTokenSource.Destroy;
begin
FToken.Free;
inherited;
end;
procedure TCancellationTokenSource.Cancel;
begin
FToken.Cancel;
end;
procedure TCancellationTokenSource.CancelAfter(ATimeoutMs: Cardinal);
begin
FToken.CancelAfter(ATimeoutMs);
end;
function TCancellationTokenSource.GetToken: TCancellationToken;
begin
Result := FToken;
end;
function TCancellationTokenSource.GetIsCancellationRequested: Boolean;
begin
Result := FToken.IsCancellationRequested;
end;
{ ======================================================
TTaskQueue
====================================================== }
constructor TTaskQueue.Create(ACapacity: Integer);
begin
inherited Create;
FCapacity := ACapacity;
SetLength(FBuf, FCapacity);
FHead := 0;
FTail := 0;
FCount := 0;
FDone := False;
InitializeCriticalSection(FCS);
FSem := CreateSemaphore(nil, 0, MaxInt, nil);
end;
destructor TTaskQueue.Destroy;
begin
CloseHandle(FSem);
DeleteCriticalSection(FCS);
inherited;
end;
procedure TTaskQueue.Grow;
var
NewBuf: TTasksArray;
NewCap: Integer;
i : Integer;
begin
NewCap := FCapacity * 2;
SetLength(NewBuf, NewCap);
for i := 0 to FCount - 1 do
NewBuf[i] := FBuf[(FHead + i) mod FCapacity];
FBuf := NewBuf;
FHead := 0;
FTail := FCount;
FCapacity := NewCap;
end;
procedure TTaskQueue.Enqueue(ATask: TTask);
begin
ATask._AddRef;
EnterCriticalSection(FCS);
try
if FCount = FCapacity then Grow;
FBuf[FTail] := ATask;
FTail := (FTail + 1) mod FCapacity;
Inc(FCount);
finally
LeaveCriticalSection(FCS);
end;
ReleaseSemaphore(FSem, 1, nil);
end;
function TTaskQueue.Dequeue: TTask;
begin
WaitForSingleObject(FSem, INFINITE);
EnterCriticalSection(FCS);
try
if FDone and (FCount = 0) then
begin
Result := nil;
Exit;
end;
if FCount > 0 then
begin
Result := FBuf[FHead];
FBuf[FHead] := nil;
FHead := (FHead + 1) mod FCapacity;
Dec(FCount);
end
else
Result := nil;
finally
LeaveCriticalSection(FCS);
end;
end;
procedure TTaskQueue.Terminate;
begin
EnterCriticalSection(FCS);
FDone := True;
LeaveCriticalSection(FCS);
ReleaseSemaphore(FSem, 512, nil);
end;
{ ======================================================
TWorkerThread
====================================================== }
constructor TWorkerThread.Create(AQueue: TTaskQueue);
begin
FQueue := AQueue;
FSyncTask := nil;
FreeOnTerminate := False;
inherited Create(False);
end;
procedure TWorkerThread.DoRunOnMain;
begin
FSyncTask.InternalExecute;
end;
procedure TWorkerThread.Execute;
var
Task: TTask;
begin
while not Terminated do
begin
Task := FQueue.Dequeue;
if Task = nil then Break;
try
if Task.FRunOnMain then
begin
FSyncTask := Task;
Synchronize(DoRunOnMain);
FSyncTask := nil;
end
else
Task.InternalExecute;
finally
Task._Release;
end;
end;
end;
{ ======================================================
TThreadPool
====================================================== }
constructor TThreadPool.Create(AWorkerCount: Integer);
var
SI: TSystemInfo;
i : Integer;
begin
inherited Create;
if AWorkerCount <= 0 then
begin
GetSystemInfo(SI);
AWorkerCount := Integer(SI.dwNumberOfProcessors) * 2;
if AWorkerCount < 2 then AWorkerCount := 2;
if AWorkerCount > 32 then AWorkerCount := 32;
end;
FCount := AWorkerCount;
FQueue := TTaskQueue.Create;
SetLength(FWorkers, FCount);
for i := 0 to FCount - 1 do
FWorkers[i] := TWorkerThread.Create(FQueue);
end;
destructor TThreadPool.Destroy;
var
i: Integer;
begin
FQueue.Terminate;
for i := 0 to FCount - 1 do
begin
FWorkers[i].Terminate;
FWorkers[i].WaitFor;
FWorkers[i].Free;
end;
SetLength(FWorkers, 0);
FQueue.Free;
inherited;
end;
procedure TThreadPool.Enqueue(ATask: TTask);
begin
FQueue.Enqueue(ATask);
end;
class function TThreadPool.Default: TThreadPool;
begin
if GDefaultPool = nil then
begin
EnterCriticalSection(GPoolCS);
try
if GDefaultPool = nil then
GDefaultPool := TThreadPool.Create;
finally
LeaveCriticalSection(GPoolCS);
end;
end;
Result := GDefaultPool;
end;
class procedure TThreadPool.ReleaseDefault;
begin
EnterCriticalSection(GPoolCS);
try
FreeAndNil(GDefaultPool);
finally
LeaveCriticalSection(GPoolCS);
end;
end;
{ ======================================================
TTask — common initialisation
====================================================== }
procedure TTask.InitFields(AData: Pointer; APool: TThreadPool);
begin
FProc := nil;
FMethod := nil;
FCancelProc := nil;
FCancelMethod := nil;
FData := AData;
FPool := APool;
FState := tsPending;
FErrorMsg := '';
FContCount := 0;
FRunOnMain := False;
FToken := nil;
FOwnsToken := False;
FCancelFlag := false;
InitializeCriticalSection(FCS);
FDoneEvent := CreateEvent(nil, True, False, nil);
end;
{ ======================================================
TTask — constructors
====================================================== }
{ Standard (no token) }
constructor TTask.Create(AProc: TTaskProc; AData: Pointer; APool: TThreadPool);
begin
inherited Create;
InitFields(AData, APool);
FProc := AProc;
end;
constructor TTask.Create(AMethod: TTaskMethod; AData: Pointer; APool: TThreadPool);
begin
inherited Create;
InitFields(AData, APool);
FMethod := AMethod;
end;
{ Standard callback + external token }
constructor TTask.Create(AProc: TTaskProc; AData: Pointer;
AToken: TCancellationToken; APool: TThreadPool);
begin
inherited Create;
InitFields(AData, APool);
FProc := AProc;
FToken := AToken; // do not own
end;
constructor TTask.Create(AMethod: TTaskMethod; AData: Pointer;
AToken: TCancellationToken; APool: TThreadPool);
begin
inherited Create;
InitFields(AData, APool);
FMethod := AMethod;
FToken := AToken;
end;
{ Cancel-aware callback + token }
constructor TTask.Create(ACancelProc: TTaskCancelProc; AData: Pointer;
AToken: TCancellationToken; AOwnsToken: Boolean; APool: TThreadPool);
begin
inherited Create;
InitFields(AData, APool);
FCancelProc := ACancelProc;
FToken := AToken;
FOwnsToken := AOwnsToken;
end;
constructor TTask.Create(ACancelMethod: TTaskCancelMethod; AData: Pointer;
AToken: TCancellationToken; AOwnsToken: Boolean; APool: TThreadPool);
begin
inherited Create;
InitFields(AData, APool);
FCancelMethod := ACancelMethod;
FToken := AToken;
FOwnsToken := AOwnsToken;
end;
{ ======================================================
TTask — destructor
====================================================== }
destructor TTask.Destroy;
var
i: Integer;
begin
for i := 0 to FContCount - 1 do
begin
FConts[i]._Release;
FConts[i] := nil;
end;
SetLength(FConts, 0);
SetLength(FContOpts, 0);
// If the task created or took ownership of the token — free it
if FOwnsToken and (FToken <> nil) then
FreeAndNil(FToken);
CloseHandle(FDoneEvent);
DeleteCriticalSection(FCS);
inherited;
end;
{ ======================================================
TTask — execution logic
====================================================== }
function TTask.IsExternalCancellationRequested: Boolean;
begin
Result := ((FCancelFlag) ) or
((FToken <> nil) and (FToken.IsCancellationRequested));
end;
procedure TTask.InternalExecute;
begin
{ -- Check cancellation BEFORE starting work -- }
if IsExternalCancellationRequested then
begin
CancelSelf;
Exit;
end;
EnterCriticalSection(FCS);
FState := tsRunning;
LeaveCriticalSection(FCS);
try
{ Cancel-aware callbacks receive the token directly }
if Assigned(FCancelProc) then
FCancelProc(FData, FToken)
else if Assigned(FCancelMethod) then
FCancelMethod(FData, FToken)
else if Assigned(FProc) then
FProc(FData)
else if Assigned(FMethod) then
FMethod(FData);
Complete('');
except
on E: ETaskCancelled do
CancelSelf; // cooperative cancellation > tsCancelled
on E: Exception do
Complete(E.Message); // error > tsFailed
end;
end;
procedure TTask.Complete(const AErrMsg: string);
begin
EnterCriticalSection(FCS);
FErrorMsg := AErrMsg;
if AErrMsg = '' then
FState := tsCompleted
else
FState := tsFailed;
LeaveCriticalSection(FCS);
SetEvent(FDoneEvent);
ScheduleContinuations;
end;
procedure TTask.CancelSelf;
begin
EnterCriticalSection(FCS);
FState := tsCancelled;
LeaveCriticalSection(FCS);
SetEvent(FDoneEvent);
ScheduleContinuations;
end;
function TTask.ShouldRunCont(AOptions: TContinuationOptions;
AParentState: TTaskState): Boolean;
begin
Result := False;
if coAlways in AOptions then
begin
Result := AParentState in [tsCompleted, tsFailed];
Exit;
end;
case AParentState of
tsCompleted: Result := coOnlyOnSuccess in AOptions;
tsFailed : Result := coOnlyOnFailed in AOptions;
// tsCancelled > continuation is not run (regardless of filter)
end;
end;
procedure TTask.ScheduleContinuations;
var
i : Integer;
ParentState: TTaskState;
Count : Integer;
SnapConts : TTasksArray;
SnapOpts : array of TContinuationOptions;
begin
EnterCriticalSection(FCS);
try
ParentState := FState;
Count := FContCount;
if Count = 0 then Exit;
SetLength(SnapConts, Count);
SetLength(SnapOpts, Count);
for i := 0 to Count - 1 do
begin
SnapConts[i] := FConts[i];
SnapOpts[i] := FContOpts[i];
FConts[i]._AddRef;
end;
finally
LeaveCriticalSection(FCS);
end;
try
for i := 0 to Count - 1 do
if ShouldRunCont(SnapOpts[i], ParentState) then
begin
SnapConts[i].FRunOnMain := coOnMainThread in SnapOpts[i];
FPool.Enqueue(SnapConts[i]);
end
else
SnapConts[i].CancelSelf;
finally
for i := 0 to Count - 1 do
SnapConts[i]._Release;
end;