/
Greenlets.pas
3001 lines (2604 loc) · 86.2 KB
/
Greenlets.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
// **************************************************************************************************
// Delphi Aio Library.
// Unit Greenlets
// 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 Greenlets.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 Greenlets;
interface
uses GInterfaces, SyncObjs, SysUtils, Classes, Gevent, GarbageCollector,
Hub, PasMP;
type
TSmartPointer<T> = record
strict private
FObjRef: IGCObject;
FRef: T;
class function IsClass: Boolean; static;
public
class operator Implicit(A: TSmartPointer<T>): T;
class operator Implicit(A: T): TSmartPointer<T>;
function Get: T;
end;
/// <summary>
/// Ensures that the coroutines addressed to the resource
/// will be queued and in the same order will be
/// access when Condition is reset. state
/// Thanks to the participation of the mutex / critical section can save ABA problems
/// </summary>
{ code example:
___ greenlet/thread no.1
Cond := TGCondVariable.Create;
....
do somethings
....
Cond.Broadcast;
___ greenlet/thread no.2
Cond.Wait; ... wait signal
___ greenlet/thread no.3
Cond.Wait; ... wait signal
}
TGCondVariable = record
strict private
Impl: IGCondVariable;
function GetImpl: IGCondVariable;
public
class function Make(aExternalMutex: TCriticalSection = nil): TGCondVariable; static;
/// <summary>
/// Wait for the signal state
/// </summary>
/// <remarks>
/// If the decision about Wait is received inside the Lock
/// will safely escape this lock inside the call Wait
/// because getting into the waiting queue must happen
/// to unLock-a and not lose state
/// </remarks>
procedure Wait(aUnlocking: TCriticalSection = nil); overload; inline;
procedure Wait(aSpinUnlocking: TPasMPSpinLock); overload; inline;
/// <summary>
/// Toss the first in the queue (if there is one)
/// </summary>
procedure Signal; inline;
/// <summary>
/// To pull all queue
/// </summary>
procedure Broadcast; inline;
end;
/// <summary>
/// Semaphore
/// </summary>
TGSemaphore = record
strict private
Impl: IGSemaphore;
public
class function Make(Limit: LongWord): TGSemaphore; static;
procedure Acquire; inline;
procedure Release; inline;
function Limit: LongWord; inline;
function Value: LongWord; inline;
end;
TGMutex = record
strict private
Impl: IGMutex;
function GetImpl: IGMutex;
public
procedure Acquire; inline;
procedure Release; inline;
end;
/// <summary>
/// A queue for synchronizing coroutines or coroutines with a thread
/// </summary>
TGQueue<T> = record
strict private
Impl: IGQueue<T>;
public
class function Make(MaxCount: LongWord = 0): TGQueue<T>; static;
procedure Enqueue(A: T); inline;
procedure Dequeue(out A: T); inline;
procedure Clear; inline;
function Count: Integer; inline;
end;
{*
The environment allows grinlets created in the text. context inherit
environment variables
*}
IGreenEnvironment = interface
procedure SetValue(const Name: string; Value: TPersistent);
function GetValue(const Name: string): TPersistent;
procedure UnsetValue(const Name: string);
procedure Clear;
// simple values
procedure SetIntValue(const Name: string; Value: Integer);
procedure SetStrValue(const Name: string; Value: string);
procedure SetFloatValue(const Name: string; Value: Single);
procedure SetDoubleValue(const Name: string; const Value: Double);
procedure SetInt64Value(const Name: string; const Value: Int64);
function GetIntValue(const Name: string): Integer;
function GetStrValue(const Name: string): string;
function GetFloatValue(const Name: string): Single;
function GetDoubleValue(const Name: string): Double;
function GetInt64Value(const Name: string): Int64;
end;
{*
Coroutine - starts the procedure on its stack
with its CPU registers with its exception handler tree
*}
TGreenlet = record
private
Impl: IGreenlet;
public
constructor Create(const Routine: TSymmetricRoutine); overload;
constructor Create(const Routine: TSymmetricArgsRoutine; const Args: array of const); overload;
constructor Create(const Routine: TSymmetricArgsStatic; const Args: array of const); overload;
procedure Run;
class function Spawn(const Routine: TSymmetricRoutine): TGreenlet; overload; static;
class function Spawn(const Routine: TSymmetricArgsRoutine;
const Args: array of const): TGreenlet; overload; static;
class function Spawn(const Routine: TSymmetricArgsStatic;
const Args: array of const): TGreenlet; overload; static;
procedure Kill;
procedure Join;
class operator Implicit(const A: TGreenlet): IGreenlet; overload;
class operator Implicit(const A: TGreenlet): TGevent; overload;
/// <summary>
/// Give Processor
/// </summary>
function Switch: tTuple; overload;
// You can transfer parameters on the move, which are Greenlet
// get through ... var X: tTuple; X: = Yield; ...
// (useful when tuning the generator on the fly)
function Switch(const Args: array of const): tTuple; overload;
// Âåðíóòü óïðàâëåíèå âûçâàâøåìó
class function Yield: tTuple; overload; static;
// Âåðíóòü óïðàâëåíèå âûçâàâøåé ìèêðîíèòêå è ïåðåäàòü äàííûå ÷åðåç î÷åðåäü Thread-à
// (óäîáíî ïðè ìàïïèíãå äàííûõ)
class function Yield(const A: array of const): tTuple; overload; static;
end;
// Generator
{ code example:
var
Gen := TGenerator<Integer>
I: Integer;
begin
Gen := TGenerator<Integer>.Create(Increment, [4, 11, 3])
for I in Gen do begin // will produce 4, 7, 10 witout allocation data in memory
-> do somethings
end
end;
procedure Increment(const Args: array of const);
var
Value, Stop, IncValue: Integer;
begin
Value := Args[0].AsInteger;
Stop := Args[1].AsInteger;
IncValue := Args[2].AsInteger;
repeat
TGenerator<Integer>.Yield(Value);
Value := Value + IncValue;
until Value > Stop;
end;
}
TGenerator<T> = record
private
Impl: IGenerator<T>;
public
constructor Create(const Routine: TSymmetricRoutine); overload;
constructor Create(const Routine: TSymmetricArgsRoutine;const Args: array of const); overload;
constructor Create(const Routine: TSymmetricArgsStatic; const Args: array of const); overload;
procedure Setup(const Args: array of const);
function GetEnumerator: GInterfaces.TEnumerator<T>;
class procedure Yield(const Value: T); static;
end;
{*
Allows you to combine machines into a group and simultaneously destroy / wait
*}
TGreenGroup<KEY> = record
private
Impl: IGreenGroup<KEY>;
function GetImpl: IGreenGroup<KEY>;
procedure SetValue(const Key: KEY; G: IRawGreenlet);
function GetValue(const Key: KEY): IRawGreenlet;
public
property Item[const Index: KEY]: IRawGreenlet read GetValue write SetValue; default;
function Join(Timeout: LongWord = INFINITE; const RaiseError: Boolean = False): Boolean;
procedure Clear;
procedure KillAll;
function IsEmpty: Boolean;
function Copy: TGreenGroup<KEY>;
function Count: Integer;
end;
TSymmetric = record
private
Impl: IRawGreenlet;
public
constructor Create(const Routine: TSymmetricRoutine); overload;
constructor Create(const Routine: TSymmetricRoutineStatic); overload;
procedure Run;
class function Spawn(const Routine: TSymmetricRoutine): TSymmetric; overload; static;
class function Spawn(const Routine: TSymmetricRoutineStatic): TSymmetric; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TSymmetric): IRawGreenlet; overload;
class operator Implicit(const A: TSymmetric): TGevent; overload;
end;
TSymmetric<T> = record
private
Impl: IRawGreenlet;
public
constructor Create(const Routine: TSymmetricRoutine<T>; const A: T); overload;
constructor Create(const Routine: TSymmetricRoutineStatic<T>; const A: T); overload;
procedure Run;
class function Spawn(const Routine: TSymmetricRoutine<T>; const A: T): TSymmetric<T>; overload; static;
class function Spawn(const Routine: TSymmetricRoutineStatic<T>; const A: T): TSymmetric<T>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TSymmetric<T>): IRawGreenlet; overload;
class operator Implicit(const A: TSymmetric<T>): TGevent; overload;
end;
TSymmetric<T1, T2> = record
private
Impl: IRawGreenlet;
public
constructor Create(const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2); overload;
constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2); overload;
procedure Run;
class function Spawn(const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; overload; static;
class function Spawn(const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TSymmetric<T1, T2>): IRawGreenlet; overload;
class operator Implicit(const A: TSymmetric<T1, T2>): TGevent; overload;
end;
TSymmetric<T1, T2, T3> = record
private
Impl: IRawGreenlet;
public
constructor Create(const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3); overload;
constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3); overload;
procedure Run;
class function Spawn(const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; overload; static;
class function Spawn(const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TSymmetric<T1, T2, T3>): IRawGreenlet; overload;
class operator Implicit(const A: TSymmetric<T1, T2, T3>): TGevent; overload;
end;
TSymmetric<T1, T2, T3, T4> = record
private
Impl: IRawGreenlet;
public
constructor Create(const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); overload;
constructor Create(const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); overload;
procedure Run;
class function Spawn(const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; overload; static;
class function Spawn(const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TSymmetric<T1, T2, T3, T4>): IRawGreenlet; overload;
class operator Implicit(const A: TSymmetric<T1, T2, T3, T4>): TGevent; overload;
end;
TAsymmetric<Y> = record
private
Impl: IAsymmetric<Y>;
public
constructor Create(const Routine: TAsymmetricRoutine<Y>); overload;
constructor Create(const Routine: TAsymmetricRoutineStatic<Y>); overload;
procedure Run;
class function Spawn(const Routine: TAsymmetricRoutine<Y>): TAsymmetric<Y>; overload; static;
class function Spawn(const Routine: TAsymmetricRoutineStatic<Y>): TAsymmetric<Y>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TAsymmetric<Y>): IRawGreenlet; overload;
class operator Implicit(const A: TAsymmetric<Y>): IAsymmetric<Y>; overload;
class operator Implicit(const A: TAsymmetric<Y>): TGevent; overload;
function GetResult(const Block: Boolean = True): Y;
{$IFDEF DCC}
class function Spawn<T>(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<Y>; overload; static;
class function Spawn<T>(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<Y>; overload; static;
class function Spawn<T1,T2>(const Routine: TAsymmetricRoutine<T1,T2,Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; overload; static;
class function Spawn<T1,T2>(const Routine: TAsymmetricRoutineStatic<T1,T2,Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; overload; static;
class function Spawn<T1,T2,T3>(const Routine: TAsymmetricRoutine<T1,T2,T3,Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; overload; static;
class function Spawn<T1,T2,T3>(const Routine: TAsymmetricRoutineStatic<T1,T2,T3,Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; overload; static;
class function Spawn<T1,T2,T3,T4>(const Routine: TAsymmetricRoutine<T1,T2,T3,T4,Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; overload; static;
class function Spawn<T1,T2,T3,T4>(const Routine: TAsymmetricRoutineStatic<T1,T2,T3,T4,Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; overload; static;
{$ENDIF}
end;
TAsymmetric<T, Y> = record
private
Impl: IAsymmetric<Y>;
public
constructor Create(const Routine: TAsymmetricRoutine<T, Y>; const A: T); overload;
constructor Create(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T); overload;
procedure Run;
class function Spawn(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<T, Y>; overload; static;
class function Spawn(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<T, Y>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TAsymmetric<T, Y>): IRawGreenlet; overload;
class operator Implicit(const A: TAsymmetric<T, Y>): IAsymmetric<Y>; overload;
class operator Implicit(const A: TAsymmetric<T, Y>): TGevent; overload;
function GetResult(const Block: Boolean = True): Y;
end;
TAsymmetric<T1, T2, Y> = record
private
Impl: IAsymmetric<Y>;
public
constructor Create(const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2); overload;
constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2); overload;
procedure Run;
class function Spawn(const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<T1, T2, Y>; overload; static;
class function Spawn(const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<T1, T2, Y>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TAsymmetric<T1, T2, Y>): IRawGreenlet; overload;
class operator Implicit(const A: TAsymmetric<T1, T2, Y>): IAsymmetric<Y>; overload;
class operator Implicit(const A: TAsymmetric<T1, T2, Y>): TGevent; overload;
function GetResult(const Block: Boolean = True): Y;
end;
TAsymmetric<T1, T2, T3, Y> = record
private
Impl: IAsymmetric<Y>;
public
constructor Create(const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3); overload;
constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3); overload;
procedure Run;
class function Spawn(const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<T1, T2, T3, Y>; overload; static;
class function Spawn(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<T1, T2, T3, Y>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TAsymmetric<T1, T2, T3, Y>): IRawGreenlet; overload;
class operator Implicit(const A: TAsymmetric<T1, T2, T3, Y>): IAsymmetric<Y>; overload;
class operator Implicit(const A: TAsymmetric<T1, T2, T3, Y>): TGevent; overload;
function GetResult(const Block: Boolean = True): Y;
end;
TAsymmetric<T1, T2, T3, T4, Y> = record
private
Impl: IAsymmetric<Y>;
public
constructor Create(const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); overload;
constructor Create(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4); overload;
procedure Run;
class function Spawn(const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<T1, T2, T3, T4, Y>; overload; static;
class function Spawn(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<T1, T2, T3, T4, Y>; overload; static;
procedure Kill;
procedure Join(const RaiseErrors: Boolean = False);
class operator Implicit(const A: TAsymmetric<T1, T2, T3, T4, Y>): IRawGreenlet; overload;
class operator Implicit(const A: TAsymmetric<T1, T2, T3, T4, Y>): IAsymmetric<Y>; overload;
class operator Implicit(const A: TAsymmetric<T1, T2, T3, T4, Y>): TGevent; overload;
function GetResult(const Block: Boolean = True): Y;
end;
TSymmetricFactory = class
strict private
FHub: THub;
public
constructor Create(Hub: THub);
function Spawn(const Routine: TSymmetricRoutine): TSymmetric; overload;
function Spawn(const Routine: TSymmetricRoutineStatic): TSymmetric; overload;
function Spawn<T>(const Routine: TSymmetricRoutine<T>; const A: T): TSymmetric<T>; overload;
function Spawn<T>(const Routine: TSymmetricRoutineStatic<T>; const A: T): TSymmetric<T>; overload;
function Spawn<T1, T2>(const Routine: TSymmetricRoutine<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; overload;
function Spawn<T1, T2>(const Routine: TSymmetricRoutineStatic<T1, T2>; const A1: T1; const A2: T2): TSymmetric<T1, T2>; overload;
function Spawn<T1, T2, T3>(const Routine: TSymmetricRoutine<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; overload;
function Spawn<T1, T2, T3>(const Routine: TSymmetricRoutineStatic<T1, T2, T3>; const A1: T1; const A2: T2; const A3: T3): TSymmetric<T1, T2, T3>; overload;
function Spawn<T1, T2, T3, T4>(const Routine: TSymmetricRoutine<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; overload;
function Spawn<T1, T2, T3, T4>(const Routine: TSymmetricRoutineStatic<T1, T2, T3, T4>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TSymmetric<T1, T2, T3, T4>; overload;
end;
TAsymmetricFactory<Y> = class
strict private
FHub: THub;
public
constructor Create(Hub: THub);
function Spawn(const Routine: TAsymmetricRoutine<Y>): TAsymmetric<Y>; overload;
function Spawn(const Routine: TAsymmetricRoutineStatic<Y>): TAsymmetric<Y>; overload;
function Spawn<T>(const Routine: TAsymmetricRoutine<T, Y>; const A: T): TAsymmetric<Y>; overload;
function Spawn<T>(const Routine: TAsymmetricRoutineStatic<T, Y>; const A: T): TAsymmetric<Y>; overload;
function Spawn<T1, T2>(const Routine: TAsymmetricRoutine<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; overload;
function Spawn<T1, T2>(const Routine: TAsymmetricRoutineStatic<T1, T2, Y>; const A1: T1; const A2: T2): TAsymmetric<Y>; overload;
function Spawn<T1, T2, T3>(const Routine: TAsymmetricRoutine<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; overload;
function Spawn<T1, T2, T3>(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, Y>; const A1: T1; const A2: T2; const A3: T3): TAsymmetric<Y>; overload;
function Spawn<T1, T2, T3, T4>(const Routine: TAsymmetricRoutine<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; overload;
function Spawn<T1, T2, T3, T4>(const Routine: TAsymmetricRoutineStatic<T1, T2, T3, T4, Y>; const A1: T1; const A2: T2; const A3: T3; const A4: T4): TAsymmetric<Y>; overload;
end;
TGreenThread = class(TThread)
class var
NumberOfInstances: Integer;
strict private
FOnTerminate: TGevent;
FHub: TSingleThreadHub;
FSymmetrics: TSymmetricFactory;
FHash: TObject;
function ExitCond: Boolean;
procedure DoAbort;
protected
procedure Execute; override;
public
constructor Create; overload;
destructor Destroy; override;
procedure Kill(const GreenBlock: Boolean = True);
function Symmetrics: TSymmetricFactory;
function Asymmetrics<Y>: TAsymmetricFactory<Y>;
end;
/// <summary>
/// Allows nonblocking write / read for channels through Select
/// </summary>
TCase<T> = record
private
Impl: ICase;
FValueHolder: TSmartPointer<T>;
FValueToWrite: IFuture<T, TPendingError>;
FValueToRead: IFuture<T, TPendingError>;
public
class operator Implicit(var A: TCase<T>): ICase;
class operator Implicit(const A: TCase<T>): T;
class operator Implicit(const A: T): TCase<T>;
class operator Equal(a: TCase<T>; b: T) : Boolean; overload;
class operator Equal(a: T; b: TCase<T>) : Boolean; overload;
function Get: T;
end;
/// <summary>
/// transmission channel, allows data to be exchanged between actors
/// 1) you can catch the closing of the channel
/// 2) As in Erlang and Scala, you can build graphs of processing from actors (implemented on greenlets)
/// linked channels
/// 3) the solution to the problem of lost-update -> after the channel is closed, you can "add" the latest data
/// 4) you can catch DeadLock-and or LeaveLock-and
/// 5) synchronous. channel with ThreadSafe = False - minimum of overheads for data transmission
/// </summary>
{ code example:
___ geenlet/thread no.1 (producer) ___
Ch := TChannel<Integer>.Make;
repeat
A := MakeData(...)
unlil not Ch.Write(A);
Ch.Close;
___ geenlet/thread no.2 (consumer) ___
while Ch.Read(Value) do begin
... // do somethings
end;
}
TChannel<T> = record
type
// readonly side
TReadOnly = record
private
Impl: IReadOnly<T>;
function GetDeadlockException: TExceptionClass;
procedure SetDeadlockEsxception(const Value: TExceptionClass);
public
class operator Implicit(const Ch: TReadOnly): IAbstractChannel;
class operator LessThan(var a: TCase<T>; const b: TReadOnly): Boolean;
function Read(out A: T): Boolean;
function ReadPending: IFuture<T, TPendingError>;
function GetEnumerator: TEnumerator<T>;
function Get: T;
procedure Close;
function IsClosed: Boolean;
property DeadlockEsxception: TExceptionClass read GetDeadlockException write SetDeadlockEsxception;
function IsNull: Boolean;
end;
// writeonly side
TWriteOnly = record
private
Impl: IWriteOnly<T>;
function GetDeadlockException: TExceptionClass;
procedure SetDeadlockEsxception(const Value: TExceptionClass);
public
class operator Implicit(const Ch: TWriteOnly): IAbstractChannel;
class operator LessThan(const a: TWriteOnly; var b: TCase<T>): Boolean;
function Write(const A: T): Boolean;
function WritePending(const A: T): IFuture<T, TPendingError>;
procedure Close;
function IsClosed: Boolean;
property DeadlockEsxception: TExceptionClass read GetDeadlockException write SetDeadlockEsxception;
function IsNull: Boolean;
end;
private
Impl: IChannel<T>;
function GetDeadlockException: TExceptionClass;
procedure SetDeadlockEsxception(const Value: TExceptionClass);
public
class function Make(Size: LongWord = 0; const ThreadSafe: Boolean = True): TChannel<T>; static;
class operator Implicit(const Ch: TChannel<T>): IChannel<T>;
class operator LessThan(var a: TCase<T>; const b: TChannel<T>): Boolean;
class operator LessThan(const a: TChannel<T>; var b: TCase<T>): Boolean;
function Read(out A: T): Boolean;
function ReadPending: IFuture<T, TPendingError>;
function Write(const A: T): Boolean;
function WritePending(const A: T): IFuture<T, TPendingError>;
function ReadOnly: TReadOnly;
function WriteOnly: TWriteOnly;
procedure Close;
function IsClosed: Boolean;
function GetEnumerator: TEnumerator<T>;
function Get: T;
property DeadlockEsxception: TExceptionClass read GetDeadlockException write SetDeadlockEsxception;
function IsNull: Boolean;
end;
/// <summary>
/// Fan - allows to duplicate copies on channels
/// </summary>
{ code example:
Ch := TChannel<Integer>.Make;
FanOut := TFanOut<Integer>.Make(Ch.ReadOnly);
Consumer1 := Spawn(Routine1, FanOut.Inflate);
Consumer2 := Spawn(Routine2, FanOut.Inflate);
....
ConsumerN := Spawn(RoutineN, FanOut.Inflate);
...
Ch.Write(1);
Ch.Write(2);
...
Ch.Write(M);
}
TFanOut<T> = record
strict private
Impl: IFanOut<T>;
public
constructor Make(const Input: TChannel<T>.TReadOnly);
function Inflate(const BufSize: Integer=-1): TChannel<T>.TReadOnly;
end;
TFuturePromise<RESULT, STATUS> = record
strict private
FFuture: IFuture<RESULT, STATUS>;
FPromise: IPromise<RESULT, STATUS>;
procedure Init;
function GetFuture: IFuture<RESULT, STATUS>;
function GetPromise: IPromise<RESULT, STATUS>;
public
property Future: IFuture<RESULT, STATUS> read GetFuture;
property Promise: IPromise<RESULT, STATUS> read GetPromise;
end;
TSwitchResult = (srClosed, srDeadlock, srTimeout,
srReadSuccess, srWriteSuccess, srException, srError);
TCaseSet = record
private
Collection: ICollection<ICase>;
function GetCollection: ICollection<ICase>;
public
class function Make(const Cases: array of ICase): TCaseSet; static;
class operator Implicit(const A: ICase): TCaseSet;
class operator Add(a: TCaseSet; b: ICase): TCaseSet;
class operator Add(a: TCaseSet; b: TCaseSet): TCaseSet;
class operator Subtract(a: TCaseSet; b: ICase) : TCaseSet;
class operator Subtract(a: TCaseSet; b: TCaseSet) : TCaseSet;
function IsEmpty: Boolean;
procedure Clear;
function Has(a: ICase): Boolean;
class operator In(a: ICase; b: TCaseSet) : Boolean;
end;
// current context
function GetCurrent: TObject;
function GetEnvironment: IGreenEnvironment;
// Greenlet context access
function Context(const Key: string): TObject; overload; // äîñòàòü çíà÷åíèå ïî êëþ÷ó
procedure Context(const Key: string; Value: TObject); overload; // óñòàíîâèòü ïî êëþ÷ó
// Garbage collector
function GC(A: TObject): IGCObject; overload;
// Return control from current Greenlet context
procedure Yield;
// Put greenlets on service in the current context
// RaiseErrors=True -> Exception in some of greenlet will be thrown out
function Join(const Workers: array of IRawGreenlet;
const Timeout: LongWord=INFINITE; const RaiseErrors: Boolean = False): Boolean;
// Join all grinlets launched in on current HUB. hub by default
function JoinAll(const Timeout: LongWord=INFINITE; const RaiseErrors: Boolean = False): Boolean;
// demultiplexer for a set of events, Index - index of the first signaled
function Select(const Events: array of TGevent; out Index: Integer;
const Timeout: LongWord=INFINITE): TWaitResult; overload;
function Select(const Events: array of THandle; out Index: Integer;
const Timeout: LongWord=INFINITE): Boolean; overload;
// Demultiplexer for channels, for nonblocking input-output
function Switch(const Cases: array of ICase; out Index: Integer;
const Timeout: LongWord=INFINITE): TSwitchResult; overload;
function Switch(var ReadSet: TCaseSet; var WriteSet: TCaseSet; var ErrorSet: TCaseSet;
const Timeout: LongWord=INFINITE): TSwitchResult; overload;
// Put the coroutine / thread on aTimeOut msec
// this does not block the work of other machines
procedure GreenSleep(aTimeOut: LongWord = INFINITE);
// jump over to another thread
procedure MoveTo(Thread: TGreenThread);
procedure BeginThread;
procedure EndThread;
// context handlers
procedure RegisterKillHandler(Cb: TThreadMethod);
procedure RegisterHubHandler(Cb: TThreadMethod);
type
TVarRecHelper = record helper for TVarRec
function IsString: Boolean;
function IsObject: Boolean;
function IsInteger: Boolean;
function IsInt64: Boolean;
function IsSingle: Boolean;
function IsDouble: Boolean;
function IsBoolean: Boolean;
function IsVariant: Boolean;
function IsClass: Boolean;
function IsPointer: Boolean;
function IsInterface: Boolean;
function AsString: string;
function AsObject: TObject;
function AsLongWord: LongWord;
function AsInteger: Integer;
function AsInt64: Int64;
function AsSingle: Single;
function AsDouble: Double;
function AsBoolean: Boolean;
function AsVariant: Variant;
function AsDateTime: TDateTime;
function AsClass: TClass;
function AsPointer: Pointer;
function AsInterface: IInterface;
function AsAnsiString: AnsiString;
procedure Finalize;
end;
implementation
uses Math, ChannelImpl, GreenletsImpl, TypInfo,
{$IFDEF FPC}
contnrs, fgl
{$ELSE}Generics.Collections, Generics.Defaults
{$ENDIF};
const
READ_SET_GUID = '{809964D9-7F70-42AE-AA37-366120DEE5A6}';
WRITE_SET_GUID = '{6FAB5314-C59A-473D-8871-E30F44CBF5C4}';
ERROR_SET_GUID = '{5768E2B8-BB72-4A87-BC06-9BCD282BE588}';
type
TRawGreenletPimpl = class(TRawGreenletImpl);
threadvar
YieldsFlag: Boolean;
function GetCurrent: TObject;
begin
Result := TRawGreenletPimpl.GetCurrent
end;
function GetEnvironment: IGreenEnvironment;
begin
Result := TRawGreenletPimpl.GetEnviron;
end;
function Context(const Key: string): TObject;
begin
if GetCurrent = nil then
Result := GetCurrentHub.HLS(Key)
else begin
Result := TRawGreenletImpl(GetCurrent).Context.GetValue(Key)
end;
end;
procedure Context(const Key: string; Value: TObject);
var
Current: TRawGreenletImpl;
Obj: TObject;
CurHub: TCustomHub;
begin
Current := TRawGreenletImpl(GetCurrent);
if Current = nil then begin
if Hub.HubInfrasctuctureEnable then begin
CurHub := GetCurrentHub;
if Assigned(CurHub) then
CurHub.HLS(Key, Value)
end;
end
else begin
if Current.Context.IsExists(Key) then begin
Obj := Current.Context.GetValue(Key);
Obj.Free;
Current.Context.UnsetValue(Key);
end;
if Assigned(Value) then
Current.Context.SetValue(Key, Value)
end;
end;
function GC(A: TObject): IGCObject;
var
Current: TRawGreenletImpl;
begin
Current := TRawGreenletImpl(GetCurrent);
if Current = nil then begin
if HubInfrasctuctureEnable then
Result := GetCurrentHub.GC(A)
else
Result := nil
end
else begin
if Current.GetState <> gsKilling then
Result := Current.GC.SetValue(A)
else
Result := nil;
end;
end;
function PendingError2SwitchStatus(const Input: TPendingError; const IO: TIOOperation): TSwitchResult;
begin
Result := srError;
case Input of
psClosed:
Result := srClosed;
psDeadlock:
Result := srDeadlock;
psTimeout:
Result := srTimeout;
psException:
Result := srException;
psSuccess: begin
case IO of
ioNotSet:
Result := srError;
ioRead:
Result := srReadSuccess;
ioWrite:
Result := srWriteSuccess;
end;
end
else
Result := srError
end;
end;
{ TVarRecHelper }
function TVarRecHelper.AsAnsiString: AnsiString;
begin
Result := GreenletsImpl.AsAnsiString(Self);
end;
function TVarRecHelper.AsBoolean: Boolean;
begin
Result := GreenletsImpl.AsBoolean(Self)
end;
function TVarRecHelper.AsClass: TClass;
begin
Result := GreenletsImpl.AsClass(Self)
end;
function TVarRecHelper.AsDateTime: TDateTime;
begin
Result := GreenletsImpl.AsDateTime(Self)
end;
function TVarRecHelper.AsDouble: Double;
begin
Result := GreenletsImpl.AsDouble(Self)
end;
function TVarRecHelper.AsInt64: Int64;
begin
Result := GreenletsImpl.AsInt64(Self)
end;
function TVarRecHelper.AsInteger: Integer;
begin
Result := GreenletsImpl.AsInteger(Self)
end;
function TVarRecHelper.AsInterface: IInterface;
begin
Result := GreenletsImpl.AsInterface(Self)
end;
function TVarRecHelper.AsLongWord: LongWord;
begin
Result := LongWord(Self.AsInteger)
end;
function TVarRecHelper.AsObject: TObject;
begin
Result := GreenletsImpl.AsObject(Self)
end;
function TVarRecHelper.AsPointer: Pointer;
begin
Result := GreenletsImpl.AsPointer(Self)
end;
function TVarRecHelper.AsSingle: Single;
begin
Result := GreenletsImpl.AsSingle(Self)
end;
function TVarRecHelper.AsString: string;
begin
Result := GreenletsImpl.AsString(Self)
end;
function TVarRecHelper.AsVariant: Variant;
begin
Result := GreenletsImpl.AsVariant(Self)
end;
procedure TVarRecHelper.Finalize;
begin
GreenletsImpl.Finalize(Self);
end;
function TVarRecHelper.IsBoolean: Boolean;
begin
Result := GreenletsImpl.IsBoolean(Self)
end;
function TVarRecHelper.IsClass: Boolean;
begin
Result := GreenletsImpl.IsClass(Self)
end;
function TVarRecHelper.IsDouble: Boolean;
begin
Result := GreenletsImpl.IsDouble(Self)
end;
function TVarRecHelper.IsInt64: Boolean;
begin
Result := GreenletsImpl.IsInt64(Self)
end;
function TVarRecHelper.IsInteger: Boolean;
begin
Result := GreenletsImpl.IsInteger(Self)
end;
function TVarRecHelper.IsInterface: Boolean;
begin
Result := GreenletsImpl.IsInterface(Self)
end;
function TVarRecHelper.IsObject: Boolean;
begin
Result := GreenletsImpl.IsObject(Self)
end;
function TVarRecHelper.IsPointer: Boolean;
begin
Result := GreenletsImpl.IsPointer(Self)
end;
function TVarRecHelper.IsSingle: Boolean;
begin
Result := GreenletsImpl.IsSingle(Self)
end;
function TVarRecHelper.IsString: Boolean;
begin
Result := GreenletsImpl.IsString(Self)
end;
function TVarRecHelper.IsVariant: Boolean;
begin
Result := GreenletsImpl.IsVariant(Self)
end;
{ TGreenlet }
constructor TGreenlet.Create(const Routine: TSymmetricRoutine);
begin
Impl := TGreenletImpl.Create(Routine);
end;
constructor TGreenlet.Create(const Routine: TSymmetricArgsRoutine;
const Args: array of const);
begin
Impl := TGreenletImpl.Create(Routine, Args);
end;
constructor TGreenlet.Create(const Routine: TSymmetricArgsStatic;
const Args: array of const);
begin
Impl := TGreenletImpl.Create(Routine, Args);
end;
class operator TGreenlet.Implicit(const A: TGreenlet): IGreenlet;
begin
Result := A.Impl
end;
class operator TGreenlet.Implicit(const A: TGreenlet): TGevent;
begin
Result := A.Impl.GetOnTerminate
end;
procedure TGreenlet.Join;
begin
Greenlets.Join([Self])
end;
procedure TGreenlet.Kill;
begin
Impl.Kill
end;
procedure TGreenlet.Run;
begin
if Impl.GetState = gsReady then
Impl.Switch
end;
class function TGreenlet.Spawn(const Routine: TSymmetricRoutine): TGreenlet;
begin
Result := TGreenlet.Create(Routine);
Result.Switch;
end;
class function TGreenlet.Spawn(const Routine: TSymmetricArgsRoutine;
const Args: array of const): TGreenlet;
begin
Result := TGreenlet.Create(Routine, Args);
Result.Switch;
end;
class function TGreenlet.Spawn(const Routine: TSymmetricArgsStatic;
const Args: array of const): TGreenlet;
begin
Result := TGreenlet.Create(Routine, Args);