forked from PavelMinenkov/AIO
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHub.pas
More file actions
1699 lines (1541 loc) · 41 KB
/
Hub.pas
File metadata and controls
1699 lines (1541 loc) · 41 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
// **************************************************************************************************
// Delphi Aio Library.
// Unit Hub
// https://github.com/Purik/AIO
// The contents of this file are subject to the Apache License 2.0 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
//
// The Original Code is Hub.pas.
//
// Contributor(s):
// Pavel Minenkov
// Purik
// https://github.com/Purik
//
// The Initial Developer of the Original Code is Pavel Minenkov [Purik].
// All Rights Reserved.
//
// **************************************************************************************************
unit Hub;
interface
uses Classes, SysUtils, SyncObjs, {$IFDEF LOCK_FREE} PasMP, {$ENDIF}
{$IFDEF FPC} fgl {$ELSE}Generics.Collections, System.Rtti{$ENDIF},
GarbageCollector, GInterfaces;
type
THub = class(TCustomHub)
strict private
type
TTaskKind = (tkMethod, tkIntfMethod, tkProc);
{ TTask }
TTask = record
Kind: TTaskKind;
Method: TThreadMethod;
Intf: IInterface;
Proc: TTaskProc;
Arg: Pointer;
procedure Init(const Method: TThreadMethod); overload;
procedure Init(Intf: IInterface; const Method: TThreadMethod); overload;
procedure Init(const Proc: TTaskProc; Arg: Pointer); overload;
{$IFDEF FPC}
class operator = (const a,b : TTask): Boolean;
{$ENDIF}
end;
TQueue = {$IFDEF DCC}TList<TTask>{$ELSE}TFPGList<TTask>{$ENDIF};
procedure GetAddresses(const Task: TThreadMethod; out Obj: TObject;
out MethodAddr: Pointer); inline;
var
FQueue: TQueue;
FAccumQueue: TQueue;
FLoopExit: Boolean;
FName: string;
FLock: SyncObjs.TCriticalSection;
FLS: Pointer;
FGC: Pointer;
FIsSuspended: Boolean;
{$IFDEF LOCK_FREE}
FLockFreeQueue: TPasMPUnboundedQueue;
{$ENDIF}
procedure Clean;
procedure Swap(var A1, A2: TQueue);
protected
procedure Lock; inline;
procedure Unlock; inline;
function TryLock: Boolean; inline;
function ServeTaskQueue: Boolean; dynamic;
procedure AfterSwap; dynamic;
public
constructor Create;
destructor Destroy; override;
property Name: string read FName write FName;
property IsSuspended: Boolean read FIsSuspended write FIsSuspended;
function HLS(const Key: string): TObject; override;
procedure HLS(const Key: string; Value: TObject); override;
function GC(A: TObject): IGCObject; override;
procedure EnqueueTask(const Task: TThreadMethod); override;
procedure EnqueueTask(const Task: TTaskProc; Arg: Pointer); override;
procedure Pulse; override;
procedure LoopExit; override;
procedure Loop(const Cond: TExitCondition; Timeout: LongWord = INFINITE); override;
procedure Loop(const Cond: TExitConditionStatic; Timeout: LongWord = INFINITE); override;
procedure Switch; override;
end;
TSingleThreadHub = class(THub)
type
TMultiplexorEvent = (meError, meEvent, meSync, meIO, meWinMsg,
meTimer, meWaitTimeout);
TMultiplexorEvents = set of TMultiplexorEvent;
const
ALL_EVENTS: TMultiplexorEvents = [Low(TMultiplexorEvent)..High(TMultiplexorEvent)];
private
type
TTimeoutRoutine = function(Timeout: LongWord): Boolean of object;
var
FEvents: Pointer;
FReadFiles: Pointer;
FWriteFiles: Pointer;
FTimeouts: Pointer;
FWakeMainThread: TNotifyEvent;
FThreadId: LongWord;
FTimerFlag: Boolean;
FIOFlag: Boolean;
FIsDef: Boolean;
FProcessWinMsg: Boolean;
FSyncEvent: TEvent;
FServeRoutine: TTimeoutRoutine;
procedure SetTriggerFlag(const TimerFlag, IOFlag: Boolean);
procedure WakeUpThread(Sender: TObject);
procedure SetupEnviron;
procedure BeforeServe;inline;
procedure AfterServe; inline;
function ServeAsDefHub(Timeout: LongWord): Boolean;
function ServeHard(Timeout: LongWord): Boolean;
protected
function ServeMultiplexor(TimeOut: LongWord): TMultiplexorEvent; dynamic;
public
constructor Create;
destructor Destroy; override;
// IO files, sockets, com-ports, pipes, etc.
procedure Cancel(Fd: THandle); override;
function Write(Fd: THandle; Buf: Pointer; Len: LongWord; const Cb: TIOCallback; Data: Pointer; Offset: Int64 = -1): Boolean; override;
function WriteTo(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean; override;
function Read(Fd: THandle; Buf: Pointer; Len: LongWord; const Cb: TIOCallback; Data: Pointer; Offset: Int64 = -1): Boolean; override;
function ReadFrom(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean; override;
// IO timeouts and timers
function CreateTimer(const Cb: TInervalCallback; Data: Pointer; Interval: LongWord): THandle; override;
procedure DestroyTimer(Id: THandle); override;
function CreateTimeout(const Cb: TInervalCallback; Data: Pointer; Interval: LongWord): THandle; override;
procedure DestroyTimeout(Id: THandle); override;
// Event objects
function AddEvent(Ev: THandle; const Cb: TEventCallback; Data: Pointer): Boolean; override;
procedure RemEvent(Ev: THandle); override;
// services
function Serve(TimeOut: LongWord): Boolean; override;
function Wait(TimeOut: LongWord; const Events: TMultiplexorEvents=[];
const ProcessWinMsg: Boolean = True): TMultiplexorEvent;
procedure Pulse; override;
end;
function GetCurrentHub: TCustomHub;
function DefHub(ThreadID: LongWord = 0): TSingleThreadHub; overload;
function DefHub(Thread: TThread): TSingleThreadHub; overload;
var
HubInfrasctuctureEnable: Boolean;
{$IFDEF DEBUG}
IOEventTupleCounter: Integer;
IOFdTupleCounter: Integer;
IOTimeTupleCounter: Integer;
{$ENDIF}
implementation
uses Math, GreenletsImpl, Greenlets, sock,
{$IFDEF MSWINDOWS}
{$IFDEF DCC}Winapi.Windows{$ELSE}windows{$ENDIF}
{$ELSE}
// TODO
{$ENDIF};
const
NANOSEC_PER_MSEC = 1000000;
type
TObjMethodStruct = packed record
Code: Pointer;
Data: TObject;
end;
THubMap = {$IFDEF DCC}TDictionary{$ELSE}TFPGMap{$ENDIF}<LongWord, TSingleThreadHub>;
TEventTuple = record
Event: THandle;
Cb: TEventCallback;
Data: Pointer;
Hub: THub;
procedure Trigger(const Aborted: Boolean);
end;
PEvents = ^TEvents;
TEvents = record
const
MAX_EV_COUNT = 1024;
var
SyncEvent: TEvent;
FBuf: array[0..MAX_EV_COUNT-1] of THandle;
FCb: array[0..MAX_EV_COUNT-1] of TEventCallback;
FData: array[0..MAX_EV_COUNT-1] of Pointer;
FHub: array[0..MAX_EV_COUNT-1] of THub;
FBufSize: Integer;
procedure Enqueue(Hnd: THandle; const Cb: TEventCallback;
Data: Pointer; Hub: THub);
procedure DequeueByIndex(Index: Integer); overload;
procedure Dequeue(Hnd: THandle); overload;
function Buf: Pointer; inline;
function TupleByIndex(Index: Integer): TEventTuple; inline;
function Find(Hnd: THandle; out Index: Integer): Boolean; inline;
function BufSize: LongWord; inline;
function IsInitialized: Boolean; inline;
procedure Initialize; inline;
procedure DeInitialize; inline;
end;
PFileTuple = ^TFileTuple;
TFileTuple = record
Fd: THandle;
ReadData: Pointer;
WriteData: Pointer;
ReadCb: TIOCallback;
WriteCb: TIOCallback;
Hub: THub;
Active: Boolean;
CleanTime: TTime;
{$IFDEF MSWINDOWS}
Overlap: TOverlapped;
{$ENDIF}
procedure RecalcCleanTime;
procedure Trigger(ErrorCode: Integer; Len: Integer; const Op: TIOOperation);
end;
PFiles = ^TFiles;
TFiles = record
const
TRASH_CLEAR_TIMEOUT_MINS = 30;
type
TMap = {$IFDEF DCC}TDictionary{$ELSE}TFPGMap{$ENDIF}<THandle, PFileTuple>;
FList = {$IFDEF DCC}TList{$ELSE}TFPGList{$ENDIF}<PFileTuple>;
var
FMap: TMap;
// in input-output operations callbacks can come to private
// descriptors. This is found for sockets
FTrash: FList;
FTrashLAstClean: TTime;
procedure TrashClean(const OnlyByTimeout: Boolean = True);
function IsInitialized: Boolean;
procedure Initialize;
procedure Deinitialize;
function Enqueue(Fd: THandle; const Op: TIOOperation;
const Cb: TIOCallback; Data: Pointer; Hub: THub): PFileTuple; overload;
procedure Dequeue(const Fd: THandle);
function Find(Fd: THandle): Boolean; overload;
function Find(Id: THandle; out Tup: PFileTuple): Boolean; overload;
end;
PTimeoutTuple = ^TTimeoutTuple;
TTimeoutTuple = record
Id: THandle;
Cb: TInervalCallback;
Data: Pointer;
Hub: THub;
procedure Trigger;
end;
TRawGreenletPImpl = class(TRawGreenletImpl);
PTimeouts = ^TTimeouts;
TTimeouts = record
type
TMap = {$IFDEF DCC}TDictionary{$ELSE}TFPGMap{$ENDIF}<THandle, PTimeoutTuple>;
var
FMap: TMap;
function IsInitialized: Boolean;
procedure Initialize;
procedure Deinitialize;
public
function Enqueue(Id: THandle; const Cb: TInervalCallback;
Data: Pointer; Hub: THub): PTimeoutTuple;
procedure Dequeue(Id: THandle);
function Find(Id: THandle): Boolean; overload;
end;
threadvar
CurrentHub: THub;
var
DefHubsLock: SyncObjs.TCriticalSection;
DefHubs: THubMap;
{$IFDEF MSWINDOWS}
{$I iocpwin.inc}
var
WsaDataOnce: TWSADATA;
function GetCurrentProcessorNumber: DWORD; external kernel32 name 'GetCurrentProcessorNumber';
{$ENDIF}
function GetCurrentHub: TCustomHub;
begin
if Assigned(CurrentHub) then
Result := CurrentHub
else
Result := DefHub;
end;
function DefHub(ThreadID: LongWord): TSingleThreadHub;
var
ID: LongWord;
CintainsKey: Boolean;
{$IFNDEF DCC}
Index: Integer;
{$ENDIF}
begin
if not Assigned(DefHubs) then
Exit(nil);
if ThreadID = 0 then
ID := TThread.CurrentThread.ThreadID
else
ID := ThreadID;
DefHubsLock.Acquire;
try
{$IFDEF DCC}
CintainsKey := DefHubs.ContainsKey(ID);
{$ELSE}
CintainsKey := DefHubs.Find(ID, Index);
{$ENDIF}
if CintainsKey then
Result := DefHubs[ID]
else begin
Result := TSingleThreadHub.Create;
Result.FIsDef := True;
Result.FThreadId := ID;
DefHubs.Add(ID, Result);
end;
finally
DefHubsLock.Release
end;
end;
function DefHub(Thread: TThread): TSingleThreadHub;
begin
Result := DefHub(Thread.ThreadID)
end;
{$IFDEF MSWINDOWS}
procedure STFileIOCompletionReadRoutine(dwErrorCode: DWORD;
dwNumberOfBytesTransfered:DWORD; lpOverlapped: POverlapped); stdcall;
var
Tuple: PFileTuple;
begin
Tuple := PFileTuple(lpOverlapped.hEvent);
if not Tuple.Active then begin
Tuple.RecalcCleanTime;
Exit;
end;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(False, True);
Tuple.Trigger(dwErrorCode, dwNumberOfBytesTransfered, ioRead);
end;
procedure STFlaggedFileIOCompletionReadRoutine(dwErrorCode: DWORD;
dwNumberOfBytesTransfered:DWORD; lpOverlapped: POverlapped; Flags: DWORD); stdcall;
var
Tuple: PFileTuple;
begin
Tuple := PFileTuple(lpOverlapped.hEvent);
if not Tuple.Active then begin
Tuple.RecalcCleanTime;
Exit;
end;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(False, True);
Tuple.Trigger(dwErrorCode, dwNumberOfBytesTransfered, ioRead);
end;
procedure STFileIOCompletionWriteRoutine(dwErrorCode: DWORD;
dwNumberOfBytesTransfered:DWORD; lpOverlapped: POverlapped); stdcall;
var
Tuple: PFileTuple;
begin
Tuple := PFileTuple(lpOverlapped.hEvent);
if not Tuple.Active then begin
Tuple.RecalcCleanTime;
Exit;
end;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(False, True);
Tuple.Trigger(dwErrorCode, dwNumberOfBytesTransfered, ioWrite);
end;
procedure STFlaggedFileIOCompletionWriteRoutine(dwErrorCode: DWORD;
dwNumberOfBytesTransfered:DWORD; lpOverlapped: POverlapped; Flags: DWORD); stdcall;
var
Tuple: PFileTuple;
begin
Tuple := PFileTuple(lpOverlapped.hEvent);
if not Tuple.Active then begin
Tuple.RecalcCleanTime;
Exit;
end;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(False, True);
Tuple.Trigger(dwErrorCode, dwNumberOfBytesTransfered, ioWrite);
end;
procedure STTimerAPCProc(lpArgToCompletionRoutine: Pointer;
dwTimerLowValue: DWORD; dwTimerHighValue: DWORD); stdcall;
var
Tuple: PTimeoutTuple;
begin
Tuple := lpArgToCompletionRoutine;
TSingleThreadHub(Tuple.Hub).SetTriggerFlag(True, False);
Tuple.Trigger;
end;
{$ENDIF}
function GetEvents(Hub: TSingleThreadHub): PEvents; inline;
begin
Result := PEvents(Hub.FEvents)
end;
function GetReadFiles(Hub: TSingleThreadHub): PFiles; inline;
begin
Result := PFiles(Hub.FReadFiles)
end;
function GetWriteFiles(Hub: TSingleThreadHub): PFiles; inline;
begin
Result := PFiles(Hub.FWriteFiles)
end;
function GetTimeouts(Hub: TSingleThreadHub): PTimeouts; inline;
begin
Result := PTimeouts(Hub.FTimeouts)
end;
{ THub }
procedure THub.AfterSwap;
begin
end;
function THub.ServeTaskQueue: Boolean;
var
I: Integer;
Arg: Pointer;
Proc: TTaskProc;
OldHub: THub;
Tsk: TTask;
procedure Process(var Tsk: TTask);
begin
case Tsk.Kind of
tkMethod: begin
Tsk.Method();
end;
tkIntfMethod: begin
if Assigned(Tsk.Intf) then begin
Tsk.Method();
Tsk.Intf := nil;
end;
end;
tkProc: begin
Proc := Tsk.Proc;
Arg := Tsk.Arg;
Proc(Arg)
end;
end;
end;
begin
Result := False;
OldHub := CurrentHub;
try
CurrentHub := Self;
{$IFDEF MSWINDOWS}
if TThread.CurrentThread.ThreadID = MainThreadID then begin
Result := CheckSynchronize(0)
end;
{$ENDIF}
{$IFDEF LOCK_FREE}
try
while FLockFreeQueue.Dequeue(Tsk) do begin
Result := True;
Process(Tsk)
end;
finally
while FLockFreeQueue.Dequeue(Tsk) do ;
end;
{$ELSE}
// transaction commit to write and transfer data
// in transaction for reading - to reduce problems with race condition
Swap(FQueue, FAccumQueue);
Result := Result or (FQueue.Count > 0);
if FQueue.Count > 0 then
try
for I := 0 to FQueue.Count-1 do begin
Tsk := FQueue[I];
Process(Tsk);
end;
finally
// obligatory it is necessary to clean, differently at Abort or Exception
// on the iteration trace. queues will come up with "outdated" calls
FQueue.Clear;
end;
{$ENDIF}
finally
CurrentHub := OldHub;
end;
end;
procedure THub.Clean;
procedure CleanQueue(A: TQueue);
var
I: Integer;
begin
for I := 0 to A.Count-1 do
with A[I] do begin
case Kind of
tkIntfMethod: begin
//Intf._Release;
end;
tkMethod:;
tkProc: ;
end;
end;
A.Clear;
end;
begin
Lock;
try
CleanQueue(FAccumQueue);
CleanQueue(FQueue);
finally
Unlock
end;
end;
procedure THub.Swap(var A1, A2: TQueue);
var
Tmp: TQueue;
begin
Lock;
try
Tmp := A1;
A1 := A2;
A2 := Tmp;
finally
AfterSwap;
Unlock;
end;
end;
procedure THub.Lock;
begin
{$IFDEF DCC}
TMonitor.Enter(FLock);
{$ELSE}
FLock.Acquire;
{$ENDIF}
end;
procedure THub.Unlock;
begin
{$IFDEF DCC}
TMonitor.Exit(FLock);
{$ELSE}
FLock.Release;
{$ENDIF}
end;
function THub.TryLock: Boolean;
begin
{$IFDEF DCC}
Result := TMonitor.TryEnter(FLock);
{$ELSE}
Result := FLock.TryEnter
{$ENDIF}
end;
constructor THub.Create;
begin
inherited Create;
FQueue := TQueue.Create;
FAccumQueue := TQueue.Create;
FLock := SyncObjs.TCriticalSection.Create;
FLS := TLocalStorage.Create;
FGC := TGarbageCollector.Create;
GetJoiner(Self);
{$IFDEF LOCK_FREE}
FLockFreeQueue := TPasMPUnboundedQueue.Create(SizeOf(TTask));
{$ENDIF}
end;
destructor THub.Destroy;
begin
Clean;
FQueue.Free;
FAccumQueue.Free;
TLocalStorage(FLS).Free;
TGarbageCollector(FGC).Free;
FLock.Free;
{$IFDEF LOCK_FREE}
FLockFreeQueue.Free;
{$ENDIF}
inherited;
end;
function THub.HLS(const Key: string): TObject;
begin
Result := TLocalStorage(FLS).GetValue(Key);
end;
procedure THub.HLS(const Key: string; Value: TObject);
var
Obj: TObject;
begin
if TLocalStorage(FLS).IsExists(Key) then begin
Obj := TLocalStorage(FLS).GetValue(Key);
Obj.Free;
TLocalStorage(FLS).UnsetValue(Key);
end;
if Assigned(Value) then
TLocalStorage(FLS).SetValue(Key, Value)
end;
function THub.GC(A: TObject): IGCObject;
var
G: TGarbageCollector;
begin
G := TGarbageCollector(FGC);
Result := G.SetValue(A);
end;
procedure THub.EnqueueTask(const Task: TTaskProc; Arg: Pointer);
var
Tsk: TTask;
{$IFDEF LOCK_FREE}
Q: TPasMPUnboundedQueue;
{$ENDIF}
begin
Tsk.Init(Task, Arg);
{$IFDEF LOCK_FREE}
FLockFreeQueue.Enqueue(Tsk);
{$ELSE}
Lock;
try
FAccumQueue.Add(Tsk);
finally
Unlock
end;
{$ENDIF}
Pulse;
end;
procedure THub.EnqueueTask(const Task: TThreadMethod);
var
Obj: TObject;
MethodAddr: Pointer;
Intf: IInterface;
Tsk: TTask;
{$IFDEF LOCK_FREE}
Q: TPasMPUnboundedQueue;
{$ENDIF}
begin
GetAddresses(Task, Obj, MethodAddr);
{$IFDEF DEBUG}
Assert(not Obj.InheritsFrom(TRawGreenletImpl), 'Enqueue Greenlet methods only by Proxy');
{$ENDIF}
if Obj.GetInterface(IInterface, Intf) then
Tsk.Init(Intf, Task)
else
Tsk.Init(Task);
{$IFDEF LOCK_FREE}
if Assigned(Intf) then
Intf._AddRef;
FLockFreeQueue.Enqueue(Tsk);
{$ELSE}
Lock;
try
// write transaction
FAccumQueue.Add(Tsk);
finally
Unlock;
end;
{$ENDIF}
Pulse;
end;
procedure THub.GetAddresses(const Task: TThreadMethod; out Obj: TObject;
out MethodAddr: Pointer);
var
Struct: TObjMethodStruct absolute Task;
begin
Obj := Struct.Data;
MethodAddr := Struct.Code;
end;
procedure THub.Loop(const Cond: TExitCondition; Timeout: LongWord);
var
Stop: TTime;
begin
FLoopExit := False;
Stop := Now + TimeOut2Time(Timeout);
while not Cond() and (Now < Stop) and (not FLoopExit) do
Serve(Time2TimeOut(Stop - Now))
end;
procedure THub.Loop(const Cond: TExitConditionStatic; Timeout: LongWord);
var
Stop: TTime;
begin
FLoopExit := False;
Stop := Now + TimeOut2Time(Timeout);
while not Cond() and (Now < Stop) and (not FLoopExit) do
Serve(Time2TimeOut(Stop - Now))
end;
procedure THub.Switch;
begin
if Greenlets.GetCurrent <> nil then begin
TRawGreenletPImpl.Switch2RootContext
end;
end;
procedure THub.LoopExit;
begin
FLoopExit := True;
Pulse;
end;
procedure THub.Pulse;
begin
end;
{ TSingleThreadHub }
function TSingleThreadHub.AddEvent(Ev: THandle; const Cb: TEventCallback;
Data: Pointer): Boolean;
var
Index: Integer;
Tup: TEventTuple;
begin
{$IFDEF MSWINDOWS}
Result := GetEvents(Self).BufSize < (MAXIMUM_WAIT_OBJECTS-1);
{$ELSE}
Result := True;
{$ENDIF}
if GetEvents(Self).Find(Ev, Index) then begin
Tup := GetEvents(Self).TupleByIndex(Index);
if (@Tup.Cb <> @Cb) or (Tup.Data <> Data) then
raise EHubError.CreateFmt('Handle %d already exists in demultiplexor queue', [Ev]);
end;
if Result then begin
GetEvents(Self).Enqueue(Ev, Cb, Data, Self);
Pulse;
end;
end;
procedure TSingleThreadHub.AfterServe;
begin
if Assigned(FWakeMainThread) then
Classes.WakeMainThread := FWakeMainThread;
if not FIsDef then
FThreadId := 0;
end;
procedure TSingleThreadHub.BeforeServe;
begin
if FIsDef then begin
if FThreadId <> TThread.CurrentThread.ThreadID then
raise EHubError.Create('Def Hub must be serving inside owner thread');
end
else begin
if FThreadId <> 0 then
raise EHubError.Create('Hub already serving by other thread');
FThreadId := TThread.CurrentThread.ThreadID;
end;
SetupEnviron;
if TThread.CurrentThread.ThreadID = MainThreadID then begin
FWakeMainThread := Classes.WakeMainThread;
Classes.WakeMainThread := Self.WakeUpThread;
end;
end;
procedure TSingleThreadHub.Cancel(Fd: THandle);
var
R, W: Boolean;
begin
R := GetReadFiles(Self).Find(Fd);
W := GetWriteFiles(Self).Find(Fd);
if W or R then begin
{$IFDEF MSWINDOWS}
CancelIo(Fd);
{$ELSE}
{$ENDIF}
end;
if R then
GetReadFiles(Self).Dequeue(Fd);
if W then
GetWriteFiles(Self).Dequeue(Fd);
end;
constructor TSingleThreadHub.Create;
begin
inherited Create;
SetupEnviron;
FServeRoutine := ServeHard;
end;
function TSingleThreadHub.CreateTimeout(const Cb: TInervalCallback;
Data: Pointer; Interval: LongWord): THandle;
var
DueTime: Int64;
TuplePtr: PTimeoutTuple;
begin
{$IFDEF MSWINDOWS}
Result := CreateWaitableTimer(nil, False, '');
DueTime := Interval*(NANOSEC_PER_MSEC div 100);
DueTime := DueTime * -1;
TuplePtr := GetTimeouts(Self).Enqueue(Result, Cb, Data, Self);
if not SetWaitableTimer(Result, DueTime, 0, @STTimerAPCProc, TuplePtr, False) then begin
GetTimeouts(Self).Dequeue(Result);
end;
{$ELSE}
{$ENDIF}
end;
function TSingleThreadHub.CreateTimer(const Cb: TInervalCallback; Data: Pointer;
Interval: LongWord): THandle;
var
DueTime: Int64;
TuplePtr: PTimeoutTuple;
begin
{$IFDEF MSWINDOWS}
Result := CreateWaitableTimer(nil, False, '');
DueTime := Interval*(NANOSEC_PER_MSEC div 100);
DueTime := DueTime * -1;
TuplePtr := GetTimeouts(Self).Enqueue(Result, Cb, Data, Self);
if not SetWaitableTimer(Result, DueTime, Interval, @STTimerAPCProc, TuplePtr, False) then begin
GetTimeouts(Self).Dequeue(Result);
end;
{$ELSE}
{$ENDIF}
end;
destructor TSingleThreadHub.Destroy;
var
ContainsKey: Boolean;
{$IFNDEF DCC}
Index: Integer;
{$ENDIF}
begin
if Assigned(FEvents) then begin
GetEvents(Self).DeInitialize;
FreeMem(FEvents, SizeOf(TEvents));
end;
if Assigned(FReadFiles) then begin
GetReadFiles(Self).Deinitialize;
FreeMem(FReadFiles, SizeOf(TFiles));
end;
if Assigned(FWriteFiles) then begin
GetWriteFiles(Self).Deinitialize;
FreeMem(FWriteFiles, SizeOf(TFiles));
end;
if Assigned(FTimeouts) then begin
GetTimeouts(Self).Deinitialize;
FreeMem(FTimeouts, SizeOf(TTimeouts));
end;
if FIsDef then begin
DefHubsLock.Acquire;
try
{$IFDEF DCC}
ContainsKey := DefHubs.ContainsKey(FThreadId);
{$ELSE}
ContainsKey := DefHubs.Find(FThreadId, Index);
{$ENDIF}
if ContainsKey then
DefHubs.Remove(FThreadId);
finally
DefHubsLock.Release
end;
end;
TRawGreenletPImpl.ClearContexts;
CurrentHub := nil;
inherited;
end;
procedure TSingleThreadHub.DestroyTimeout(Id: THandle);
begin
{$IFDEF MSWINDOWS}
if GetTimeouts(Self).Find(Id) then begin
CancelWaitableTimer(Id);
GetTimeouts(Self).Dequeue(Id);
end
{$ELSE}
{$ENDIF}
end;
procedure TSingleThreadHub.DestroyTimer(Id: THandle);
begin
{$IFDEF MSWINDOWS}
if GetTimeouts(Self).Find(Id) then begin
CancelWaitableTimer(Id);
GetTimeouts(Self).Dequeue(Id);
end;
{$ELSE}
{$ENDIF}
end;
procedure TSingleThreadHub.Pulse;
begin
FSyncEvent.SetEvent;
end;
function TSingleThreadHub.ReadFrom(Fd: THandle; Buf: Pointer; Len: LongWord; const Addr: TAnyAddress; const Cb: TIOCallback; Data: Pointer): Boolean;
var
TuplePtr: PFileTuple;
Flags: DWORD;
Buf_: WSABUF;
RetValue: LongWord;
begin
TuplePtr := GetReadFiles(Self).Enqueue(Fd, ioRead, Cb, Data, Self);
Flags := MSG_PARTIAL;
Buf_.len := Len;
Buf_.buf := Buf;
WSARecvFrom(Fd, @Buf_, 1, nil, Flags, Addr.AddrPtr,
@Addr.AddrLen, @TuplePtr.Overlap, @STFlaggedFileIOCompletionReadRoutine);
RetValue := WSAGetLastError;
Result := RetValue = WSA_IO_PENDING;
if not Result then begin
GetReadFiles(Self).Dequeue(Fd);
end;
end;
function TSingleThreadHub.Read(Fd: THandle; Buf: Pointer; Len: LongWord;
const Cb: TIOCallback; Data: Pointer; Offset: Int64): Boolean;
var
TuplePtr: PFileTuple;
begin
TuplePtr := GetReadFiles(Self).Enqueue(Fd, ioRead, Cb, Data, Self);
{$IFDEF MSWINDOWS}
if Offset <> -1 then begin
TuplePtr^.Overlap.Offset := Offset and $FFFFFFFF;
TuplePtr^.Overlap.OffsetHigh := Offset shr 32;
end;
Result := ReadFileEx(Fd, Buf, Len, @TuplePtr^.Overlap, @STFileIOCompletionReadRoutine);
if not Result then
GetReadFiles(Self).Dequeue(Fd);
{$IFDEF DEBUG}
//raise EHubError.CreateFmt('Error Message: %s', [SysErrorMessage(GetLastError)]);
{$ENDIF}
{$ELSE}
{$ENDIF}
end;
procedure TSingleThreadHub.RemEvent(Ev: THandle);
begin
GetEvents(Self).Dequeue(Ev);
end;
function TSingleThreadHub.ServeAsDefHub(Timeout: LongWord): Boolean;
var
Stop: TTime;
MxEvent: TMultiplexorEvent;
begin
Stop := Now + TimeOut2Time(TimeOut);
repeat
if ServeTaskQueue then
Exit(True)
else begin
FProcessWinMsg := True;
MxEvent := ServeMultiplexor(Time2TimeOut(Stop - Now));
Result := MxEvent <> meWaitTimeout;
Result := Result or ServeTaskQueue;
end;
until (Now >= Stop) or Result;
end;
function TSingleThreadHub.ServeHard(Timeout: LongWord): Boolean;
begin
BeforeServe;
try
Result := ServeAsDefHub(Timeout);
finally
AfterServe
end;
if FIsDef then
FServeRoutine := ServeAsDefHub
end;
function TSingleThreadHub.Serve(TimeOut: LongWord): Boolean;
begin
Result := FServeRoutine(TimeOut);