-
Notifications
You must be signed in to change notification settings - Fork 0
/
ChannelImpl.pas
2461 lines (2242 loc) · 61 KB
/
ChannelImpl.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
unit ChannelImpl;
interface
uses {$IFDEF FPC} contnrs, fgl {$ELSE}Generics.Collections, System.Rtti{$ENDIF},
GInterfaces, Hub, Gevent, PasMP, Classes, Greenlets, SyncObjs,
GarbageCollector, SysUtils;
type
ILightGevent = interface
procedure SetEvent(const Async: Boolean = False);
procedure WaitEvent;
procedure Associate(Other: ILightGevent; Index: Integer);
function GetIndex: Integer;
procedure SetIndex(Value: Integer);
function GetContext: Pointer;
function GetInstance: Pointer;
end;
TLightGevent = class(TInterfacedObject, ILightGevent)
strict private
FSignal: Boolean;
FLock: TPasMPSpinLock;
FContext: Pointer;
FHub: TCustomHub;
FWaitEventRoutine: TThreadMethod;
FIndex: Integer;
FAssociate: ILightGevent;
FAssociateIndex: Integer;
FWaiting: Boolean;
procedure Lock; inline;
procedure Unlock; inline;
procedure ThreadedWaitEvent;
procedure GreenletWaitEvent;
public
constructor Create;
destructor Destroy; override;
procedure SetEvent(const Async: Boolean = False);
procedure WaitEvent;
procedure Associate(Other: ILightGevent; Index: Integer);
function GetIndex: Integer;
procedure SetIndex(Value: Integer);
function GetContext: Pointer;
function GetInstance: Pointer;
end;
IAbstractContract = interface
['{E27E9F47-02E7-4F82-BB5E-36FE142BF55B}']
procedure FixCurContext;
function IsMyCtx: Boolean;
procedure Lock;
procedure Unlock;
end;
IContract<T> = interface(IAbstractContract)
['{4A32E6FB-1E6C-462F-BF8B-0503270D162A}']
function Push(const A: T; Ref: IGCObject): Boolean;
function Pop(out A: T; out Ref: IGCObject): Boolean;
function IsEmpty: Boolean;
end;
TLightCondVar = class
type
TSyncMethod = (smDefault, smForceAsync, smForceSync);
strict private
type
TWaitRoutine = procedure(Unlocking: TPasMPSpinLock) of object;
TSyncRoutine = procedure(const Method: TSyncMethod=smDefault) of object;
var
FItems: TList;
FLock: TPasMPSpinLock;
FAsync: Boolean;
FWaitRoutine: TWaitRoutine;
FSignalRoutine: TSyncRoutine;
FBroadcastRoutine: TSyncRoutine;
procedure Clean;
procedure LockedWait(Unlocking: TPasMPSpinLock);
procedure LockedSignal(const Method: TSyncMethod);
procedure LockedBroadcast(const Method: TSyncMethod);
procedure UnLockedWait(Unlocking: TPasMPSpinLock);
procedure UnLockedSignal(const Method: TSyncMethod);
procedure UnLockedBroadcast(const Method: TSyncMethod);
protected
procedure Lock; inline;
procedure Unlock; inline;
procedure Enqueue(E: TLightGevent);
function Dequeue(out E: TLightGevent): Boolean;
public
constructor Create(const Async: Boolean; const Locked: Boolean);
destructor Destroy; override;
procedure Wait(Unlocking: TPasMPSpinLock = nil);
procedure Signal(const Method: TSyncMethod=smDefault);
procedure Broadcast(const Method: TSyncMethod=smDefault);
procedure Assign(Source: TLightCondVar);
end;
TAbstractContractImpl = class(TInterfacedObject, IAbstractContract)
strict private
FLock: TPasMPSpinLock;
FContext: Pointer;
FHub: TCustomHub;
public
constructor Create;
destructor Destroy; override;
procedure Lock;
procedure Unlock;
procedure FixCurContext;
function IsMyCtx: Boolean;
end;
TContractImpl<T> = class(TAbstractContractImpl, IContract<T>)
strict private
FValue: T;
FDefValue: T;
FIsEmpty: Boolean;
FSmartObj: IGCObject;
public
constructor Create;
destructor Destroy; override;
function Push(const A: T; Ref: IGCObject): Boolean;
function Pop(out A: T; out Ref: IGCObject): Boolean;
function IsEmpty: Boolean;
end;
THubRefDictionary = TPasMPHashTable<THub, Integer>;
TLocalContextService = class
strict private
FRef: IGCObject;
FDeadLockExceptionClass: TExceptionClass;
function GetDeadLockExceptionClass: TExceptionClass;
public
function Refresh(A: TObject): IGCObject;
property DeadLockExceptionClass: TExceptionClass read GetDeadLockExceptionClass
write FDeadLockExceptionClass;
end;
TLeaveLockLogger = class
strict private
const
MAX_COUNT_FACTOR = 5;
var
FCounter: Integer;
public
procedure Check(const Msg: string);
end;
TOnDieEvent = procedure(ID: Integer) of object;
ILiveToken = interface
['{7A8A9717-8D55-439B-B142-80F62BC6A613}']
procedure Die;
procedure Deactivate;
function IsLive: Boolean;
end;
IContextRef = interface
procedure SetActive(const Value: Boolean);
function GetActive: Boolean;
function GetRefCount: Integer;
function AddRef(Accum: Integer = 1): Integer;
function Release(Accum: Integer = 1): Integer;
end;
TContextRef = class(TInterfacedObject, IContextRef)
strict private
FActive: Boolean;
FRefCount: Integer;
FIsOwner: Boolean;
public
constructor Create(const Active: Boolean = True; const IsOwnerContext: Boolean = False);
procedure SetActive(const Value: Boolean);
function GetActive: Boolean;
function GetRefCount: Integer;
function AddRef(Accum: Integer = 1): Integer;
function Release(Accum: Integer = 1): Integer;
end;
TContextHashTable = {$IFDEF DCC}
TDictionary<NativeUInt, IContextRef>
{$ELSE}
TFPGMap<NativeUInt, IContextRef>
{$ENDIF};
TOnGetLocalService = function: TLocalContextService of object;
TOnCheckDeadLock = function(const AsReader: Boolean; const AsWriter: Boolean;
const RaiseError: Boolean = True; const Lock: Boolean = True): Boolean of object;
TCustomChannel<T> = class(TInterfacedObject)
type
TPendingOperations<Y> = class
strict private
FPendingReader: IRawGreenlet;
FPendingWriter: IRawGreenlet;
FReaderFuture: IFuture<Y, TPendingError>;
FWriterFuture: IFuture<Y, TPendingError>;
public
destructor Destroy; override;
property PendingReader: IRawGreenlet read FPendingReader write FPendingReader;
property PendingWriter: IRawGreenlet read FPendingWriter write FPendingWriter;
property ReaderFuture: IFuture<Y, TPendingError> read FReaderFuture write FReaderFuture;
property WriterFuture: IFuture<Y, TPendingError> read FWriterFuture write FWriterFuture;
end;
strict private
FGuid: string;
FIsClosed: Integer;
FIsObjectTyp: Boolean;
function GetLocalContextKey: string;
function GetLocalPendingKey: string;
private
var
FReaders: TContextHashTable;
FWriters: TContextHashTable;
FDefValue: T;
protected
var
FLock: TPasMPSpinLock;
FReadersNum: Integer;
FWritersNum: Integer;
FOwnerContext: NativeUInt;
class function GetContextUID: NativeUInt;
property Guid: string read FGuid;
function GetLocalService: TLocalContextService;
function GetLocalPendings: TPendingOperations<T>;
property IsObjectTyp: Boolean read FIsObjectTyp;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod); virtual; abstract;
function CheckDeadLock(const AsReader: Boolean; const AsWriter: Boolean;
const RaiseError: Boolean = True; const Lock: Boolean = True): Boolean;
procedure CheckLeaveLock;
function InternalAddRef(const AsReader: Boolean; const AsWriter: Boolean): Integer;
function InternalRelease(const AsReader: Boolean; const AsWriter: Boolean): Integer;
function InternalRead(out A: T; ReleaseFactor: Integer): Boolean; dynamic; abstract;
function InternalWrite(const A: T; ReleaseFactor: Integer): Boolean; dynamic; abstract;
procedure AsyncRead(const Promise: IPromise<T, TPendingError>; const ReleaseFactor: Integer);
procedure AsyncWrite(const Promise: IPromise<T, TPendingError>; const ReleaseFactor: Integer;
const Value: TSmartPointer<T>);
public
constructor Create;
destructor Destroy; override;
// channel interface
function Read(out A: T): Boolean;
function Write(const A: T): Boolean;
function ReadPending: IFuture<T, TPendingError>;
function WritePending(const A: T): IFuture<T, TPendingError>;
procedure Close; dynamic;
function IsClosed: Boolean;
// generator-like
function Get: T;
function GetEnumerator: TEnumerator<T>;
function GetBufSize: LongWord; dynamic; abstract;
procedure AccumRefs(ReadRefCount, WriteRefCount: Integer);
procedure ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
procedure SetDeadlockExceptionClass(Cls: TExceptionClass);
function GetDeadlockExceptionClass: TExceptionClass;
end;
TReadOnlyChannel<T> = class(TInterfacedObject, IReadOnly<T>)
strict private
FParent: TCustomChannel<T>;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create(Parent: TCustomChannel<T>);
function Read(out A: T): Boolean;
function ReadPending: IFuture<T, TPendingError>;
procedure Close;
function IsClosed: Boolean;
function GetEnumerator: TEnumerator<T>;
function Get: T;
function GetBufSize: LongWord;
procedure AccumRefs(ReadRefCount, WriteRefCount: Integer);
procedure ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
procedure SetDeadlockExceptionClass(Cls: TExceptionClass);
function GetDeadlockExceptionClass: TExceptionClass;
end;
TWriteOnlyChannel<T> = class(TInterfacedObject, IWriteOnly<T>)
strict private
FParent: TCustomChannel<T>;
protected
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
public
constructor Create(Parent: TCustomChannel<T>);
function Write(const A: T): Boolean;
function WritePending(const A: T): IFuture<T, TPendingError>;
procedure Close;
function IsClosed: Boolean;
function GetBufSize: LongWord;
procedure AccumRefs(ReadRefCount, WriteRefCount: Integer);
procedure ReleaseRefs(ReadRefCount, WriteRefCount: Integer);
procedure SetDeadlockExceptionClass(Cls: TExceptionClass);
function GetDeadlockExceptionClass: TExceptionClass;
end;
TSingleThreadSyncChannel<T> = class;
TMultiThreadSyncChannel<T> = class;
TSyncChannel<T> = class(TCustomChannel<T>, IChannel<T>)
private
type
TOnRead = function(out A: T; ReleaseFactor: Integer): Boolean of object;
TOnWrite = function(const A: T; ReleaseFactor: Integer): Boolean of object;
TOnBroadcast = procedure(const Method: TLightCondVar.TSyncMethod) of object;
var
FReadOnly: TReadOnlyChannel<T>;
FWriteOnly: TWriteOnlyChannel<T>;
FSTChannel: TSingleThreadSyncChannel<T>;
FMTChannel: TMultiThreadSyncChannel<T>;
FOnRead: TOnRead;
FOnWrite: TOnWrite;
FOnClose: TThreadMethod;
FOnBroadCast: TOnBroadcast;
protected
FLiveToken: ILiveToken;
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod); override;
function InternalRead(out A: T; ReleaseFactor: Integer): Boolean; override;
function InternalWrite(const A: T; ReleaseFactor: Integer): Boolean; override;
public
constructor Create(const ThreadSafe: Boolean);
destructor Destroy; override;
procedure Close; override;
function ReadOnly: IReadOnly<T>;
function WriteOnly: IWriteOnly<T>;
function GetBufSize: LongWord; override;
end;
TAsyncChannel<T> = class(TCustomChannel<T>, IChannel<T>)
strict private
FSize: Integer;
FCapacity: Integer;
FReadOnly: TReadOnlyChannel<T>;
FWriteOnly: TWriteOnlyChannel<T>;
FItems: array of IContract<T>;
FReadOffset: Integer;
FWriteOffset: Integer;
FReadCond: TLightCondVar;
FWriteCond: TLightCondVar;
protected
FLiveToken: ILiveToken;
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod); override;
function InternalRead(out A: T; ReleaseFactor: Integer): Boolean; override;
function InternalWrite(const A: T; ReleaseFactor: Integer): Boolean; override;
public
constructor Create(BufSize: LongWord);
destructor Destroy; override;
procedure Close; override;
function ReadOnly: IReadOnly<T>;
function WriteOnly: IWriteOnly<T>;
function GetBufSize: LongWord; override;
end;
TChannelEnumerator<T> = class(TEnumerator<T>)
strict private
FChannel: TCustomChannel<T>;
FCurrent: T;
FReleaseFactor: Integer;
protected
function GetCurrent: T; override;
public
constructor Create(Channel: TCustomChannel<T>; ReleaseFator: Integer);
function MoveNext: Boolean; override;
property Current: T read GetCurrent;
procedure Reset; override;
end;
TSingleThreadSyncChannel<T> = class
const
YIELD_WAIT_CNT = 2;
type
TContract = record
strict private
SmartObj: IGCObject;
public
Value: T;
Contragent: Pointer;
IsEmpty: Boolean;
procedure PushSmartObj(Value: IGCObject);
function PullSmartObj: IGCObject;
end;
strict private
var
FContractExists: Boolean;
FReadCond: TLightCondVar;
FWriteCond: TLightCondVar;
FContract: TContract;
FHub: TCustomHub;
FIsClosed: Boolean;
FIsObjectTyp: Boolean;
FOnGetLocalService: TOnGetLocalService;
FOnCheckDeadLock: TOnCheckDeadLock;
FWritersNumPtr: PInteger;
FReadersNumPtr: PInteger;
public
constructor Create(const IsObjectTyp: Boolean;
const OnGetLocalGC: TOnGetLocalService;
const OnCheckDeadLock: TOnCheckDeadLock; WNumPtr, RNumPtr: PInteger);
destructor Destroy; override;
function Write(const A: T; ReleaseFactor: Integer): Boolean;
function Read(out A: T; ReleaseFactor: Integer): Boolean;
procedure Close;
property Hub: TCustomHub read FHub write FHub;
procedure Assign(Source: TMultiThreadSyncChannel<T>);
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod);
end;
TMultiThreadSyncChannel<T> = class
strict private
FLock: TPasMPSpinLock;
FReadCond: TLightCondVar;
FWriteCond: TLightCondVar;
FIsClosed: Boolean;
FContract: IContract<T>;
FContractExists: Boolean;
FNotify: ILightGevent;
FIsObjectTyp: Boolean;
FOnGetLocalService: TOnGetLocalService;
FOnCheckDeadLock: TOnCheckDeadLock;
FWritersNumPtr: PInteger;
FReadersNumPtr: PInteger;
protected
property Lock: TPasMPSpinLock read FLock;
property Contract: IContract<T> read FContract;
property ContractExists: Boolean read FContractExists write FContractExists;
property Notify: ILightGevent read FNotify write FNotify;
property ReadCond: TLightCondVar read FReadCond;
property WriteCond: TLightCondVar read FWriteCond;
public
constructor Create(const IsObjectTyp: Boolean;
const OnGetLocalGC: TOnGetLocalService;
const OnCheckDeadLock: TOnCheckDeadLock; WNumPtr, RNumPtr: PInteger);
destructor Destroy; override;
function Write(const A: T; ReleaseFactor: Integer): Boolean;
function Read(out A: T; ReleaseFactor: Integer): Boolean;
procedure Close;
procedure BroadcastAll(const Method: TLightCondVar.TSyncMethod);
end;
TSoftDeadLock = class(EAbort);
TFanOutImpl<T> = class(TInterfacedObject, IFanOut<T>)
strict private
type
IReadChannel = IReadOnly<T>;
TChannelDescr = record
ID: Integer;
Token: ILiveToken;
SyncImpl: TSyncChannel<T>;
AsyncImpl: TAsyncChannel<T>;
Channel: TCustomChannel<T>;
end;
var
FLastID: Integer;
FBufSize: LongWord;
FLock: TCriticalSection;
FInflateList: TList<TChannelDescr>;
FWorker: IRawGreenlet;
FWorkerContext: NativeUInt;
FWorkerCtxReady: TGevent;
FOnUpdated: TGevent;
procedure Routine(const Input: IReadOnly<T>);
procedure DieCb(ID: Integer);
function GenerateID: Integer;
public
constructor Create(Input: IReadOnly<T>);
destructor Destroy; override;
function Inflate(const BufSize: Integer=-1): IReadOnly<T>;
end;
TLiveTokenImpl = class(TInterfacedObject, ILiveToken)
strict private
FIsLive: Boolean;
FCb: TOnDieEvent;
FID: Integer;
FLock: TCriticalSection;
public
constructor Create(ID: Integer; const Cb: TOnDieEvent);
destructor Destroy; override;
function IsLive: Boolean;
procedure Die;
procedure Deactivate;
end;
var
StdDeadLockException: TExceptionClass;
StdLeaveLockException: TExceptionClass;
implementation
uses TypInfo, GreenletsImpl, Math;
type
TRawGreenletPImpl = class(TRawGreenletImpl);
function _GetCurentHub: TCustomHub;
begin
if GetCurrent <> nil then
Result := TRawGreenletPImpl(GetCurrent).Hub
else
Result := GetCurrentHub
end;
{ TSyncChannel<T> }
procedure TSyncChannel<T>.BroadcastAll(const Method: TLightCondVar.TSyncMethod);
begin
FOnBroadCast(Method);
end;
procedure TSyncChannel<T>.Close;
begin
inherited;
FOnClose;
CheckLeaveLock;
end;
constructor TSyncChannel<T>.Create(const ThreadSafe: Boolean);
begin
inherited Create;
FReadOnly := TReadOnlyChannel<T>.Create(Self);
FWriteOnly := TWriteOnlyChannel<T>.Create(Self);
if ThreadSafe then begin
FMTChannel := TMultiThreadSyncChannel<T>.Create(IsObjectTyp,
GetLocalService, CheckDeadLock, @FWritersNum, @FReadersNum);
FOnRead := FMTChannel.Read;
FOnWrite := FMTChannel.Write;
FOnClose := FMTChannel.Close;
FOnBroadCast := FMTChannel.BroadcastAll;
end
else begin
FSTChannel := TSingleThreadSyncChannel<T>.Create(IsObjectTyp,
GetLocalService, CheckDeadLock, @FWritersNum, @FReadersNum);
FOnRead := FSTChannel.Read;
FOnWrite := FSTChannel.Write;
FOnClose := FSTChannel.Close;
FOnBroadCast := FSTChannel.BroadcastAll;
end;
end;
destructor TSyncChannel<T>.Destroy;
begin
if Assigned(FLiveToken) then
FLiveToken.Die;
FReadOnly.Free;
FWriteOnly.Free;
FSTChannel.Free;
FMTChannel.Free;
inherited;
end;
function TSyncChannel<T>.GetBufSize: LongWord;
begin
Result := 0
end;
function TSyncChannel<T>.InternalRead(out A: T;
ReleaseFactor: Integer): Boolean;
begin
Result := FOnRead(A, ReleaseFactor);
if not Result then begin
CheckLeaveLock;
end;
end;
function TSyncChannel<T>.InternalWrite(const A: T;
ReleaseFactor: Integer): Boolean;
begin
Result := FOnWrite(A, ReleaseFactor);
if not Result then
CheckLeaveLock;
end;
function TSyncChannel<T>.ReadOnly: IReadOnly<T>;
begin
Result := FReadOnly
end;
function TSyncChannel<T>.WriteOnly: IWriteOnly<T>;
begin
Result := FWriteOnly
end;
{ TAsyncChannel<T> }
procedure TAsyncChannel<T>.BroadcastAll(const Method: TLightCondVar.TSyncMethod);
begin
FReadCond.Broadcast(Method);
FWriteCond.Broadcast(Method);
end;
procedure TAsyncChannel<T>.Close;
begin
inherited;
FReadCond.Broadcast(smForceAsync);
FWriteCond.Broadcast(smForceAsync);
CheckLeaveLock;
end;
constructor TAsyncChannel<T>.Create(BufSize: LongWord);
var
I: Integer;
begin
inherited Create;
Assert(BufSize > 0, 'BufSize > 0');
FCapacity := BufSize;
FReadOnly := TReadOnlyChannel<T>.Create(Self);
FWriteOnly := TWriteOnlyChannel<T>.Create(Self);
SetLength(FItems, BufSize);
for I := 0 to High(FItems) do
FItems[I] := TContractImpl<T>.Create;
FReadCond := TLightCondVar.Create(False, True);
FWriteCond := TLightCondVar.Create(True, True);
end;
destructor TAsyncChannel<T>.Destroy;
begin
if Assigned(FLiveToken) then
FLiveToken.Die;
FReadOnly.Free;
FWriteOnly.Free;
FReadCond.Free;
FWriteCond.Free;
inherited;
end;
function TAsyncChannel<T>.GetBufSize: LongWord;
begin
Result := FCapacity
end;
function TAsyncChannel<T>.InternalRead(out A: T;
ReleaseFactor: Integer): Boolean;
var
Contract: IContract<T>;
ObjPtr: PObject;
Ref: IGCObject;
begin
Result := False;
AtomicDecrement(FWritersNum, ReleaseFactor);
try
while True do begin
FLock.Acquire;
if FSize > 0 then begin
Contract := FItems[FReadOffset];
if not Contract.IsMyCtx then begin
FReadOffset := (FReadOffset + 1) mod FCapacity;
Dec(FSize);
Contract.Pop(A, Ref);
FLock.Release;
FWriteCond.Signal;
Exit(True);
end
else begin
FWriteCond.Broadcast;
if CheckDeadLock(True, False, False, False) then begin
FLock.Release;
raise GetLocalService.DeadLockExceptionClass.Create('DeadLock::TAsyncChannel<T>.Read');
end;
FReadCond.Wait(FLock);
end;
end
else begin
if IsClosed then begin
FLock.Release;
Exit(False)
end
else begin
if CheckDeadLock(True, False, False, False) then begin
FLock.Release;
raise GetLocalService.DeadLockExceptionClass.Create('DeadLock::TAsyncChannel<T>.Read');
end;
FReadCond.Wait(FLock);
end;
end;
end;
finally
AtomicIncrement(FWritersNum, ReleaseFactor);
if Result and IsObjectTyp then begin
ObjPtr := @A;
GetLocalService.Refresh(ObjPtr^);
end;
if not Result then begin
CheckLeaveLock;
end;
end;
end;
function TAsyncChannel<T>.InternalWrite(const A: T;
ReleaseFactor: Integer): Boolean;
var
Contract: IContract<T>;
ObjPtr: PObject;
Ref: IGCObject;
begin
if IsObjectTyp then begin
ObjPtr := @A;
Ref := GetLocalService.Refresh(ObjPtr^);
end;
Result := False;
AtomicDecrement(FReadersNum, ReleaseFactor);
try
while not IsClosed do begin
FLock.Acquire;
if CheckDeadLock(False, True, False, False) then begin
FLock.Release;
raise GetLocalService.DeadLockExceptionClass.Create('DeadLock::TAsyncChannel<T>.Write');
end;
if FSize < FCapacity then begin
Contract := FItems[FWriteOffset];
FWriteOffset := (FWriteOffset + 1) mod FCapacity;
Inc(FSize);
Contract.Push(A, Ref);
Contract.FixCurContext;
FLock.Release;
FReadCond.Signal;
Exit(True);
end
else begin
FReadCond.Broadcast;
FWriteCond.Wait(FLock);
end;
end;
finally
AtomicIncrement(FReadersNum, ReleaseFactor);
end;
if not Result then
CheckLeaveLock;
end;
function TAsyncChannel<T>.ReadOnly: IReadOnly<T>;
begin
Result := FReadOnly;
end;
function TAsyncChannel<T>.WriteOnly: IWriteOnly<T>;
begin
Result := FWriteOnly;
end;
{ TCustomChannel<T> }
procedure TCustomChannel<T>.AccumRefs(ReadRefCount, WriteRefCount: Integer);
var
Context: NativeUInt;
OldRefCount: Integer;
begin
Context := GetContextUID;
FLock.Acquire;
if FReaders.ContainsKey(Context) then begin
OldRefCount := FReaders[Context].GetRefCount;
FReaders[Context].AddRef(ReadRefCount);
if (FReaders[Context].GetRefCount > 0) and (OldRefCount <= 0) then
AtomicIncrement(FReadersNum);
end;
if FWriters.ContainsKey(Context) then begin
OldRefCount := FWriters[Context].GetRefCount;
FWriters[Context].AddRef(WriteRefCount);
if (FWriters[Context].GetRefCount > 0) and (OldRefCount <= 0) then
AtomicIncrement(FReadersNum);
end;
FLock.Release;
end;
procedure TCustomChannel<T>.AsyncRead(const Promise: IPromise<T, TPendingError>; const ReleaseFactor: Integer);
var
Value: T;
begin
InternalAddRef(True, False);
try
SetDeadlockExceptionClass(TSoftDeadLock);
try
if InternalRead(Value, 0) then
Promise.SetResult(Value)
else
Promise.SetErrorCode(psClosed)
except
on E: TSoftDeadLock do
Promise.SetErrorCode(psDeadlock);
on E: Exception do
Promise.SetErrorCode(psException, Format('%s::%s', [E.ClassName, E.Message]));
end;
finally
InternalRelease(True, False);
end;
end;
procedure TCustomChannel<T>.AsyncWrite(const Promise: IPromise<T, TPendingError>;
const ReleaseFactor: Integer; const Value: TSmartPointer<T>);
begin
InternalAddRef(False, True);
try
SetDeadlockExceptionClass(TSoftDeadLock);
try
if InternalWrite(Value, 0) then
Promise.SetResult(Value)
else
Promise.SetErrorCode(psClosed)
except
on E: TSoftDeadLock do
Promise.SetErrorCode(psDeadlock);
on E: Exception do
Promise.SetErrorCode(psException, Format('%s::%s', [E.ClassName, E.Message]));
end;
finally
InternalRelease(False, True);
end;
end;
function TCustomChannel<T>.CheckDeadLock(const AsReader: Boolean; const AsWriter: Boolean;
const RaiseError: Boolean; const Lock: Boolean): Boolean;
begin
{$IFDEF DEBUG}
Assert(AsReader <> AsWriter);
Assert(AsReader or AsWriter);
{$ENDIF}
if IsClosed then
Exit(False);
if Lock then
FLock.Acquire;
if AsReader then begin
Result := FWritersNum < 1
end
else begin
Result := FReadersNum < 1;
end;
if Lock then
FLock.Release;
if Result and RaiseError then
raise GetLocalService.DeadLockExceptionClass.Create('DeadLock::TCustomChannel<T>');
end;
procedure TCustomChannel<T>.CheckLeaveLock;
var
Key: string;
Inst: TLeaveLockLogger;
begin
if IsClosed then begin
Key := Format('LeaveLocker_%s', [Guid]);
Inst := TLeaveLockLogger(Context(Key));
if not Assigned(Inst) then begin
Inst := TLeaveLockLogger.Create;
Context(Key, Inst);
end;
Inst.Check('LeaveLock::TCustomChannel<T>');
end;
end;
procedure TCustomChannel<T>.Close;
var
Contract: IContract<T>;
begin
FIsClosed := 1;
end;
constructor TCustomChannel<T>.Create;
var
UID: TGUID;
ti: PTypeInfo;
begin
if CreateGuid(UID) = 0 then
FGuid := GUIDToString(UID)
else
FGuid := Format('Channel.%p', [Pointer(Self)]);
ti := TypeInfo(T);
FIsObjectTyp := ti.Kind = tkClass;
if FIsObjectTyp then
GetLocalService;
FReaders := TContextHashTable.Create(2);
FWriters := TContextHashTable.Create(2);
FLock := TPasMPSpinLock.Create;
FOwnerContext := GetContextUID;
end;
destructor TCustomChannel<T>.Destroy;
begin
Context(GetLocalContextKey, nil);
FReaders.Free;
FWriters.Free;
FLock.Free;
inherited;
end;
function TCustomChannel<T>.Get: T;
begin
if not Read(Result) then
raise EChannelClosed.Create('Channel is closed');
end;
class function TCustomChannel<T>.GetContextUID: NativeUInt;
begin
if GetCurrent = nil then
Result := NativeUInt(GetCurrentHub)
else
Result := NativeUInt(GetCurrent)
end;
function TCustomChannel<T>.GetDeadlockExceptionClass: TExceptionClass;
begin
Result := GetLocalService.DeadLockExceptionClass;
if not Assigned(Result) then
Result := StdDeadLockException;
end;
function TCustomChannel<T>.GetEnumerator: TEnumerator<T>;
begin
Result := TChannelEnumerator<T>.Create(Self, 1)
end;
function TCustomChannel<T>.GetLocalService: TLocalContextService;
var
Key: string;
begin
Key := GetLocalContextKey;
Result := TLocalContextService(Context(Key));
if not Assigned(Result) then begin
Result := TLocalContextService.Create;
Context(Key, Result);
end;
end;
function TCustomChannel<T>.GetLocalContextKey: string;
begin
Result := Format('LocalGC_%s', [Guid]);
end;
function TCustomChannel<T>.GetLocalPendingKey: string;
begin
Result := Format('Pendings_%s', [Guid]);
end;
function TCustomChannel<T>.GetLocalPendings: TPendingOperations<T>;
var
Key: string;
begin
Key := GetLocalPendingKey;
Result := TPendingOperations<T>(Context(Key));
if not Assigned(Result) then begin
Result := TPendingOperations<T>.Create;
Context(Key, Result);
end;
end;
function TCustomChannel<T>.InternalAddRef(const AsReader, AsWriter: Boolean): Integer;
var
Context: NativeUInt;
begin
Context := GetContextUID;
FLock.Acquire;
Inc(FRefCount);
Result := FRefCount;
if AsReader then begin
if FReaders.ContainsKey(Context) then
FReaders[Context].AddRef
else begin
FReaders.Add(Context, TContextRef.Create(True, Context = FOwnerContext));
AtomicIncrement(FReadersNum);
end;
end;
if AsWriter then begin
if FWriters.ContainsKey(Context) then
FWriters[Context].AddRef
else begin
FWriters.Add(Context, TContextRef.Create(True, Context = FOwnerContext));
AtomicIncrement(FWritersNum);
end;
end;
FLock.Release;
end;
function TCustomChannel<T>.InternalRelease(const AsReader, AsWriter: Boolean): Integer;
var
Context: NativeUInt;
DeadLock: Boolean;
begin
DeadLock := False;
Context := GetContextUID;
FLock.Acquire;
Dec(FRefCount);
Result := FRefCount;
if AsReader and FReaders.ContainsKey(Context) then begin
if FReaders[Context].Release = 0 then begin
AtomicDecrement(FReadersNum);
FReaders.Remove(Context);
end;
end;
if AsWriter and FWriters.ContainsKey(Context) then begin
if FWriters[Context].Release = 0 then begin
AtomicDecrement(FWritersNum);
FWriters.Remove(Context);
end;
end;
DeadLock := CheckDeadLock(False, True, False, False) or CheckDeadLock(True, False, False, False);
FLock.Release;
if DeadLock then
BroadcastAll(smForceAsync);
if Result = 0 then
Destroy;
end;