-
Notifications
You must be signed in to change notification settings - Fork 140
/
OtlContainers.pas
1901 lines (1753 loc) · 66.3 KB
/
OtlContainers.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
///<summary>Microlocking containers. Part of the OmniThreadLibrary project.</summary>
///<remarks>TOmni[Base]Queue requires Pentium 4 processor (or newer) unless OTL_OLDCPU is defined.</remarks>
///<author>Primoz Gabrijelcic, GJ</author>
///<license>
///This software is distributed under the BSD license.
///
///Copyright (c) 2019 Primoz Gabrijelcic
///All rights reserved.
///
///Redistribution and use in source and binary forms, with or without modification,
///are permitted provided that the following conditions are met:
///- Redistributions of source code must retain the above copyright notice, this
/// list of conditions and the following disclaimer.
///- Redistributions in binary form must reproduce the above copyright notice,
/// this list of conditions and the following disclaimer in the documentation
/// and/or other materials provided with the distribution.
///- The name of the Primoz Gabrijelcic may not be used to endorse or promote
/// products derived from this software without specific prior written permission.
///
///THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
///ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
///WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
///DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
///ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
///(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
///LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
///ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
///(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
///SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///</license>
///<remarks><para>
/// Home : http://www.omnithreadlibrary.com
/// Support : https://en.delphipraxis.net/forum/32-omnithreadlibrary/
/// Author : Primoz Gabrijelcic
/// E-Mail : primoz@gabrijelcic.org
/// Blog : http://thedelphigeek.com
/// Contributors : GJ, Sean B. Durkin
/// Creation date : 2008-07-13
/// Last modification : 2018-04-17
/// Version : 3.02b
///</para><para>
/// History:
/// 3.02b: 2018-04-17
/// - Fixed race condition in TOmniBaseBoundedQueue.RemoveLink which could cause
/// TOmniBaseBoundedQueue.Enqueue to return False when queue was empty.
/// 3.02a: 2017-04-06
/// - Compiles with Delphi 10.2 Tokyo.
/// 3.02: 2015-10-03
/// - Imported mobile support by [Sean].
/// 3.01a: 2012-12-05
/// - Prevent memory leak if (Queue|Stack).Initialize is called more than once
/// (thx to [h.hasenack]).
/// 3.01: 2012-11-09
/// - TOmniBaseBounded(Queue|Stack) internally aligns allocated memory to required
/// CAS granularity (8 bytes on 32-bit platforms, 16 bytes on 64-bit platforms).
/// - TOmniBaseBoundedQueue's ring buffers are internally aligned to 2*SizeOf(pointer).
/// 3.0: 2011-12-19
/// - [GJ] Implemented 64-bit TOmni[Base]Bounded(Queue|Stack).
/// - Fixed TOmni[Base]Queue to work in 64-bit world.
/// 2.05: 2011-08-26
/// - Implemented TOmni[Base]Queue.IsEmpty. Keep in mind that the returned value may
/// not be valid for any ammount of time if other threads are reading from/
/// writing to the queue.
/// 2.04: 2010-07-01
/// - Includes OTLOptions.inc.
/// 2.03a: 2010-05-06
/// - Fixed memory leak in TOmni[Base]Queue when queueing String, WideString,
/// Variant and Extended values.
/// 2.03: 2010-02-18
/// - Reversed head and tail because they were used illogically.
/// 2.02a: 2010-02-09
/// - Dynamically allocate head/tail structures so that they are allways 8-allocated.
/// - Optimized algorithm using atomic move instead of atomic compare-and-swap in
/// some places (thanks to GJ).
/// 2.02: 2010-02-08
/// - New ABA- and MREW-free dynamic queue algorithm.
/// - Dynamic queue parameters are settable in the constructor.
/// 2.01: 2010-02-04
/// - Uses CAS8 instead of CAS32.
/// 2.0: 2009-12-25
/// - Implemented dynamically allocated, O(1) enqueue and dequeue, threadsafe,
/// microlocking queue. Class TOmniBaseQueue contains base implementation
/// while TOmniQueue adds notification support.
/// - Big class rename: TOmniBaseStack -> TOmniBaseBoundedStack,
/// TOmniStack -> TOmniBoundedStack, TOmniBaseQueue -> TOmniBaseBoundedQueue,
/// TOmniQueue -> TOmniBoundedQueue.
/// 1.02: 2009-12-22
/// - TOmniContainerSubject moved into OtlContainerObserver because it will also be
/// used in OtlCollections.
/// 1.01b: 2009-11-11
/// - [GJ] better fix for the initialization crash.
/// 1.01a: 2009-11-10
/// - Bug fixed: Initialization code could crash with range check error.
/// 1.01: 2008-10-26
/// - [GJ] Redesigned stack with better lock contention.
/// - [GJ] Totally redesigned queue, which is no longer based on stack and allows
/// multiple readers.
///</para></remarks>
unit OtlContainers;
{$I OtlOptions.inc}
{$OPTIMIZATION ON}
{$WARN SYMBOL_PLATFORM OFF}
{$IFNDEF CPUX64}
{$DEFINE OTL_OLDCPU} // undefine if you're sure your code will only run on a CPU that supports SSE2 instruction set (more specifically, Move64 instruction)
{$ENDIF ~CPUX64}
//DEFINE DEBUG_OMNI_QUEUE to enable assertions in TOmniBaseQueue
//We don't have a platform-independant way of using cmpx8b/cmpx16b
//(5-parameter OtlSync.CAS) so we can't use bus-locking on non-Windows targets.
{$IFDEF MSWINDOWS}
{$DEFINE OTL_HaveCmpx16b}
{$ELSE}
{$UNDEF OTL_HaveCmpx16b}
{$ENDIF ~MSWINDOWS}
interface
uses
Classes,
OtlCommon,
OtlSync,
SyncObjs,
{$IFDEF MSWINDOWS}
DSiWin32,
GpStuff,
{$ENDIF}
OtlContainerObserver;
const
CPartlyEmptyLoadFactor = 0.8; // When an element count drops below 80%, the container is considered 'partly empty'.
CAlmostFullLoadFactor = 0.9; // When an element count raises above 90%, the container is considered 'almost full'.
type
{:Lock-free, multiple writer, multiple reader, bounded stack.
}
IOmniStack = interface ['{F4C57327-18A0-44D6-B95D-2D51A0EF32B4}']
procedure Empty;
procedure Initialize(numElements, elementSize: integer);
function IsEmpty: boolean;
function IsFull: boolean;
function Pop(var value): boolean;
function Push(const value): boolean;
end; { IOmniStack }
{:Lock-free, multiple writer, multiple reader ring buffer (bounded queue).
}
IOmniQueue = interface ['{AE6454A2-CDB4-43EE-9F1B-5A7307593EE9}']
function Dequeue(var value): boolean;
procedure Empty;
function Enqueue(const value): boolean;
procedure Initialize(numElements, elementSize: integer);
function IsEmpty: boolean;
function IsFull: boolean;
end; { IOmniQueue }
{$IFDEF OTL_MobileSupport}
IOmniValueQueue = interface ['{3399B817-0502-4837-B1D7-BA167E8E03A7}']
function GetContainerSubject: TOmniContainerSubject;
function IsEmpty: boolean;
function Dequeue: TOmniValue;
procedure Enqueue(const value: TOmniValue);
function TryDequeue(var value: TOmniValue): boolean;
property ContainerSubject: TOmniContainerSubject read GetContainerSubject;
end; { IOmniValueQueue }
{$ENDIF OTL_MobileSupport}
PReferencedPtr = ^TReferencedPtr;
TReferencedPtr = record
{$IFNDEF OTL_HaveCmpx16b}[Volatile]{$ENDIF}
PData : pointer;
{$IFDEF OTL_HaveCmpx16b} // references are only used in bus-locked implementation
Reference: NativeInt;
{$ENDIF}
end; { TReferencedPtr }
TReferencedPtrBuffer = array [0..MaxInt shr 5] of TReferencedPtr;
POmniRingBuffer = ^TOmniRingBuffer;
TOmniRingBuffer = packed record
FirstIn : TReferencedPtr;
Dummy : array[1..128 - SizeOf(TReferencedPtr)] of byte; // push LastIn into next cache line
LastIn : TReferencedPtr;
StartBuffer : pointer;
EndBuffer : pointer;
Buffer : TReferencedPtrBuffer;
end; { TOmniRingBuffer }
POmniLinkedData = ^TOmniLinkedData;
TOmniLinkedData = packed record
Next: POmniLinkedData;
Data: record end; //user data, variable size
end; { TOmniLinkedData }
TOmniBaseBoundedStack = class abstract(TInterfacedObject, IOmniStack)
strict private
obsDataBuffer : pointer;
obsElementSize : integer;
obsNumElements : integer;
obsPublicChainP : PReferencedPtr;
obsRecycleChainP: PReferencedPtr;
{$IFNDEF OTL_HaveCmpx16b}
obsLock : IOmniCriticalSection;
{$ENDIF ~OTL_HaveCmpx16b}
class var
class var obsIsInitialized: boolean; //default is false
class var obsTaskPopLoops : NativeInt;
class var obsTaskPushLoops: NativeInt;
strict protected
procedure Acquire; inline;
procedure Release; inline;
procedure MeasureExecutionTimes;
class function PopLink(var chain: TReferencedPtr): POmniLinkedData; static;
class procedure PushLink(const link: POmniLinkedData; var chain: TReferencedPtr); static;
public
constructor Create;
destructor Destroy; override;
procedure Empty;
procedure Initialize(numElements, elementSize: integer); virtual;
function IsEmpty: boolean; inline;
function IsFull: boolean; inline;
function Pop(var value): boolean;
function Push(const value): boolean;
property ElementSize: integer read obsElementSize;
property NumElements: integer read obsNumElements;
end; { TOmniBaseBoundedStack }
TOmniBoundedStack = class(TOmniBaseBoundedStack)
strict private
osAlmostFullCount : integer;
osContainerSubject: TOmniContainerSubject;
osInStackCount : TOmniAlignedInt32;
osPartlyEmptyCount: integer;
public
constructor Create(numElements, elementSize: integer;
partlyEmptyLoadFactor: real = CPartlyEmptyLoadFactor;
almostFullLoadFactor: real = CAlmostFullLoadFactor);
destructor Destroy; override;
function Pop(var value): boolean;
function Push(const value): boolean;
property ContainerSubject: TOmniContainerSubject read osContainerSubject;
end; { TOmniBoundedStack }
TOmniBaseBoundedQueue = class abstract(TInterfacedObject, IOmniQueue)
strict private
obqDataBuffer : pointer;
obqElementSize : integer;
obqNumElements : integer;
obqPublicRingBuffer : POmniRingBuffer;
obqPublicRingMem : pointer;
obqRecycleRingBuffer: POmniRingBuffer;
obqRecycleRingMem : pointer;
{$IFNDEF OTL_HaveCmpx16b}
obqLock : IOmniCriticalSection;
{$ENDIF ~OTL_HaveCmpx16b}
class var
class var obqIsInitialized : boolean;
class var obqTaskInsertLoops: NativeInt; //default is false
class var obqTaskRemoveLoops: NativeInt;
strict protected
procedure Acquire; inline;
procedure Release; inline;
class procedure InsertLink(const data: pointer; const ringBuffer: POmniRingBuffer);
static;
procedure MeasureExecutionTimes;
class function RemoveLink(const ringBuffer: POmniRingBuffer): pointer; static;
public
constructor Create;
destructor Destroy; override;
function Dequeue(var value): boolean;
procedure Empty;
function Enqueue(const value): boolean;
procedure Initialize(numElements, elementSize: integer); virtual;
function IsEmpty: boolean;
function IsFull: boolean;
property ElementSize: integer read obqElementSize;
property NumElements: integer read obqNumElements;
end; { TOmniBaseBoundedQueue }
TOmniBoundedQueue = class(TOmniBaseBoundedQueue)
strict private
oqAlmostFullCount : integer;
oqContainerSubject: TOmniContainerSubject;
oqInQueueCount : TOmniAlignedInt32;
oqPartlyEmptyCount: integer;
public
constructor Create(numElements, elementSize: integer;
partlyEmptyLoadFactor: real = CPartlyEmptyLoadFactor;
almostFullLoadFactor: real = CAlmostFullLoadFactor);
destructor Destroy; override;
function Dequeue(var value): boolean;
function Enqueue(const value): boolean;
property ContainerSubject: TOmniContainerSubject read oqContainerSubject;
end; { TOmniBoundedQueue }
TOmniQueueTag = (tagFree, tagAllocating, tagAllocated, tagRemoving,
tagEndOfList, tagExtending, tagBlockPointer, tagDestroying, tagHeader,
tagSentinel);
TOmniTaggedValue = packed record
Value : TOmniValue; //aligned for faster data access; overlaps with header's unreleased slot count, which must be pointer-aligned
Tag : TOmniQueueTag;
Offset : word;
{$IFDEF CPUX64}
Stuffing: array[1..4] of byte; // make TOmniTaggedValue 3 pointers big
{$ENDIF CPUX64}
function CASTag(oldTag, newTag: TOmniQueueTag): boolean; inline; // atomic on Windows, composite on other platforms
end; { TOmniTaggedValue }
POmniTaggedValue = ^TOmniTaggedValue;
TOmniTaggedPointer = packed record
Slot : POmniTaggedValue;
Tag : TOmniQueueTag;
{$IFNDEF CPUX64}
Stuffing: array [1..3] of byte; // record size must be congruent to 0 (mod 4)
{$ELSE CPUX64}
Stuffing: array [1..7] of byte; // record size must be congruent to 0 (mod 8)
{$ENDIF CPUX64}
function CAS(
oldSlot: POmniTaggedValue; oldTag: TOmniQueueTag;
newSlot: POmniTaggedValue; newTag: TOmniQueueTag): boolean; inline; // atomic on Windows, composite on other platforms
procedure Move(newSlot: POmniTaggedValue; newTag: TOmniQueueTag); inline; // atomic on Windows, composite on other platforms
end; { TOmniTaggedPointer }
POmniTaggedPointer = ^TOmniTaggedPointer;
///<summary>Dynamically allocated, O(1) enqueue and dequeue, threadsafe, microlocking queue.</summary>
TOmniBaseQueue = class
strict private // keep 4-aligned
obcCachedBlock: POmniTaggedValue;
strict private
obcBlockSize : integer;
obcHeadPointer: POmniTaggedPointer;
obcMemStack : TOmniBaseBoundedStack;
obcNumSlots : integer;
obcTailPointer: POmniTaggedPointer;
{$IFNDEF OTL_HaveCmpx16b}
obcLock : IOmniCriticalSection;
{$ENDIF ~OTL_HaveCmpx16b}
strict protected
{$IFDEF DEBUG_OMNI_QUEUE}
procedure Assert(condition: boolean);
{$ENDIF DEBUG_OMNI_QUEUE}
strict protected
procedure Acquire; inline;
function AllocateBlock: POmniTaggedValue;
procedure Cleanup; virtual;
procedure Initialize; virtual;
function NextSlot(slot: POmniTaggedValue): POmniTaggedValue; inline;
procedure PartitionMemory(memory: POmniTaggedValue);
procedure PreallocateMemory;
function PrevSlot(slot: POmniTaggedValue): POmniTaggedValue; inline;
procedure Release; inline;
procedure ReleaseBlock(firstSlot: POmniTaggedValue; forceFree: boolean = false);
public
constructor Create(blockSize: integer = 65536; numCachedBlocks: integer = 4);
destructor Destroy; override;
function Dequeue: TOmniValue;
procedure Enqueue(const value: TOmniValue);
function IsEmpty: boolean;
function TryDequeue(var value: TOmniValue): boolean;
end; { TOmniBaseQueue }
TOmniQueue = class(TOmniBaseQueue)
strict private
ocContainerSubject: TOmniContainerSubject;
strict protected
procedure Cleanup; override;
procedure Initialize; override;
public
function Dequeue: TOmniValue;
procedure Enqueue(const value: TOmniValue);
function TryDequeue(var value: TOmniValue): boolean;
property ContainerSubject: TOmniContainerSubject read ocContainerSubject;
end; { TOmniQueue }
{$IFDEF OTL_MobileSupport}
/// <param name="UseBusLocking">Set to true to use a spinlock. Otherwise synchronisation is achieved by a critical section.</param>
/// <param name="ThresholdForFull">The count of OmniValues to which if the queue reaches or exceeds, it is considered full.
/// Use a a value of -1 to indicate there is no threshold (and hence events like coiNotifyOnAlmostFull will never fire).</param>
function CreateOmniValueQueue(UseBusLocking: boolean; ThresholdForFull: integer = -1): IOmniValueQueue;
{$ENDIF OTL_MobileSupport}
implementation
uses
{$IFDEF MSWINDOWS}
Windows,
{$ENDIF MSWINDOWS}
{$IFDEF OTL_MobileSupport}
Generics.Collections,
{$ENDIF OTL_MobileSupport}
SysUtils;
{$IFDEF OTL_MobileSupport}
type
TInterestSet = set of TOmniContainerObserverInterest;
TOmniValueQueue = class(TInterfacedObject, IOmniValueQueue)
strict private
FAlmostFullThreshold : integer;
FContainerSubject : TOmniContainerSubject;
FFullThreshold : integer;
FInnerQueue : TQueue<TOmniValue>;
FNotifiableEvents : TInterestSet;
FPartlyEmptyThreshold: integer;
strict private
procedure CollectionNotifyEvent(Sender: TObject; const Item: TOmniValue; Action: TCollectionNotification);
function Dequeue: TOmniValue;
procedure DoWithCritSec( Proc: TProc);
procedure Enqueue(const value: TOmniValue);
function GetContainerSubject: TOmniContainerSubject;
function IsEmpty: boolean;
procedure PropagateNotifications(Events: TInterestSet);
function TryDequeue(var value: TOmniValue): boolean;
protected
procedure EnterCriticalSection; virtual; abstract;
procedure LeaveCriticalSection; virtual; abstract;
public
constructor Create(AThresholdForFull: integer);
destructor Destroy; override;
end; { TOmniValueQueue }
TOmniValueQueueCS = class(TOmniValueQueue)
strict private
FCritSect: TFixedCriticalSection;
protected
procedure EnterCriticalSection; override;
procedure LeaveCriticalSection; override;
public
constructor Create(AThresholdForFull: integer);
destructor Destroy; override;
end; { TOmniValueQueueCS }
TOmniValueQueueSpin = class(TOmniValueQueue)
strict private
FLock: TSpinLock;
protected
procedure EnterCriticalSection; override;
procedure LeaveCriticalSection; override;
public
constructor Create(AThresholdForFull: integer);
end; { TOmniValueQueueSpin }
function CreateOmniValueQueue(UseBusLocking: boolean; ThresholdForFull: integer = -1): IOmniValueQueue;
begin
if UseBusLocking then
Result := TOmniValueQueueSpin.Create(ThresholdForFull)
else
Result := TOmniValueQueueCS.Create(ThresholdForFull)
end; { CreateOmniValueQueue }
{$ENDIF OTL_MobileSupport}
{$IFDEF MSWINDOWS}
{$IFDEF CPUX64}
procedure AsmInt3;
asm
.noframe
int 3
end; { AsmInt3 }
procedure AsmPause;
asm
.noframe
pause;
end; { AsmPause }
{$ENDIF CPUX64}
{$ENDIF MSWINDOWS}
function RoundUpTo(value: pointer; granularity: integer): pointer;
begin
Result := pointer((((NativeInt(value) - 1) div granularity) + 1) * granularity);
end; { RoundUpTo }
{ TOmniBaseBoundedStack }
constructor TOmniBaseBoundedStack.Create;
begin
inherited Create;
{$IFNDEF OTL_HaveCmpx16b}
obsLock := CreateOmniCriticalSection;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedStack.Create }
destructor TOmniBaseBoundedStack.Destroy;
begin
FreeMem(obsDataBuffer);
inherited;
end; { TOmniBaseBoundedStack.Destroy }
procedure TOmniBaseBoundedStack.Acquire; //inline
begin
{$IFNDEF OTL_HaveCmpx16b}
obsLock.Acquire;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedStack.Acquire }
procedure TOmniBaseBoundedStack.Release; //inline
begin
{$IFNDEF OTL_HaveCmpx16b}
obsLock.Release;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedStack.Release }
procedure TOmniBaseBoundedStack.Empty;
var
linkedData: POmniLinkedData;
begin
repeat
linkedData := PopLink(obsPublicChainP^);
if not assigned(linkedData) then
break; //repeat
PushLink(linkedData, obsRecycleChainP^);
until false;
end; { TOmniBaseBoundedStack.Empty }
procedure TOmniBaseBoundedStack.Initialize(numElements, elementSize: integer);
var
bufferElementSize : integer;
currElement : POmniLinkedData;
dataBuffer : pointer;
iElement : integer;
nextElement : POmniLinkedData;
roundedElementSize: integer;
begin
Assert(SizeOf(NativeInt) = SizeOf(pointer));
Assert(numElements > 0);
Assert(elementSize > 0);
obsNumElements := numElements;
obsElementSize := elementSize;
//calculate element size, round up to next aligned value
roundedElementSize := (elementSize + SizeOf(pointer) - 1) AND NOT (SizeOf(pointer) - 1);
//calculate buffer element size, round up to next aligned value
bufferElementSize := ((SizeOf(TOmniLinkedData) + roundedElementSize) + SizeOf(pointer) - 1) AND NOT (SizeOf(pointer) - 1);
//calculate DataBuffer
FreeMem(obsDataBuffer);
GetMem(obsDataBuffer, bufferElementSize * numElements + 2 * SizeOf(TReferencedPtr) + CASAlignment);
dataBuffer := RoundUpTo(obsDataBuffer, CASAlignment);
if NativeInt(dataBuffer) AND (SizeOf(pointer) - 1) <> 0 then
raise Exception.Create('TOmniBaseContainer: obcBuffer is not aligned');
obsPublicChainP := dataBuffer;
inc(NativeInt(dataBuffer), SizeOf(TReferencedPtr));
obsRecycleChainP := dataBuffer;
inc(NativeInt(dataBuffer), SizeOf(TReferencedPtr));
//Format buffer to recycleChain, init obsRecycleChain and obsPublicChain.
//At the beginning, all elements are linked into the recycle chain.
obsRecycleChainP^.PData := dataBuffer;
currElement := obsRecycleChainP^.PData;
for iElement := 0 to obsNumElements - 2 do begin
nextElement := POmniLinkedData(NativeInt(currElement) + bufferElementSize);
currElement.Next := nextElement;
currElement := nextElement;
end;
currElement.Next := nil; // terminate the chain
obsPublicChainP^.PData := nil;
MeasureExecutionTimes;
end; { TOmniBaseBoundedStack.Initialize }
function TOmniBaseBoundedStack.IsEmpty: boolean;
begin
Result := not assigned(obsPublicChainP^.PData);
end; { TOmniBaseBoundedStack.IsEmpty }
function TOmniBaseBoundedStack.IsFull: boolean;
begin
Result := not assigned(obsRecycleChainP^.PData);
end; { TOmniBaseBoundedStack.IsFull }
procedure TOmniBaseBoundedStack.MeasureExecutionTimes;
const
NumOfSamples = 10;
var
TimeTestField: array [0..1] of array [1..NumOfSamples] of int64;
function GetMinAndClear(routine, count: cardinal): int64;
var
m: cardinal;
n: integer;
x: integer;
begin
Result := 0;
for m := 1 to count do begin
x:= 1;
for n:= 2 to NumOfSamples do
if TimeTestField[routine, n] < TimeTestField[routine, x] then
x := n;
Inc(Result, TimeTestField[routine, x]);
TimeTestField[routine, x] := MaxLongInt;
end;
end; { GetMinAndClear }
var
{$IFDEF MSWINDOWS}
affinity : string;
{$ENDIF MSWINDOWS}
currElement: POmniLinkedData;
n : integer;
begin { TOmniBaseBoundedStack.MeasureExecutionTimes }
if not obsIsInitialized then begin
{$IFDEF MSWINDOWS}
affinity := DSiGetThreadAffinity;
DSiSetThreadAffinity(affinity[1]);
try
{$ENDIF MSWINDOWS}
//Calculate TaskPopDelay and TaskPushDelay counter values depend on CPU speed!!!}
obsTaskPopLoops := 1;
obsTaskPushLoops := 1;
for n := 1 to NumOfSamples do begin
{$IFDEF OTL_HasTThreadYield}TThread.Yield;{$ELSE}DSiYield;{$ENDIF}
//Measure RemoveLink rutine delay
TimeTestField[0, n] := GetCPUTimeStamp;
currElement := PopLink(obsRecycleChainP^);
TimeTestField[0, n] := GetCPUTimeStamp - TimeTestField[0, n];
//Measure InsertLink rutine delay
TimeTestField[1, n] := GetCPUTimeStamp;
PushLink(currElement, obsRecycleChainP^);
TimeTestField[1, n] := GetCPUTimeStamp - TimeTestField[1, n];
end;
//Calculate first 4 minimum average for RemoveLink rutine
obsTaskPopLoops := GetMinAndClear(0, 4) div 4;
//Calculate first 4 minimum average for InsertLink rutine
obsTaskPushLoops := GetMinAndClear(1, 4) div 4;
obsIsInitialized := true;
{$IFDEF MSWINDOWS}
finally DSiSetThreadAffinity(affinity); end;
{$ENDIF MSWINDOWS}
end;
end; { TOmniBaseBoundedStack.MeasureExecutionTimes }
function TOmniBaseBoundedStack.Pop(var value): boolean;
var
linkedData: POmniLinkedData;
begin
Acquire;
try
linkedData := PopLink(obsPublicChainP^);
Result := assigned(linkedData);
if not Result then
Exit;
Move(linkedData.Data, value, ElementSize);
PushLink(linkedData, obsRecycleChainP^);
finally Release; end;
end; { TOmniBaseBoundedStack.Pop }
class function TOmniBaseBoundedStack.PopLink(var chain: TReferencedPtr): POmniLinkedData;
//nil << Link.Next << Link.Next << ... << Link.Next
// ^------ < chainHead
var
AtStartReference: NativeInt;
CurrentReference: NativeInt;
TaskCounter : NativeInt;
ThreadReference : NativeInt;
label
TryAgain;
begin
{$IFDEF OTL_HaveCmpx16b}
ThreadReference := OtlSync.GetThreadId + 1; //Reference.bit0 := 1
with chain do begin
TryAgain:
TaskCounter := obsTaskPopLoops;
AtStartReference := Reference OR 1; //Reference.bit0 := 1
repeat
CurrentReference := Reference;
Dec(TaskCounter);
until (TaskCounter = 0) or (CurrentReference AND 1 = 0);
if (CurrentReference AND 1 <> 0) and (AtStartReference <> CurrentReference) or
not TInterlockedEx.CAS(CurrentReference, ThreadReference, Reference)
then
goto TryAgain;
//Reference is set...
Result := PData;
//Empty test
if result = nil then
TInterlockedEx.CAS(ThreadReference, 0, Reference) //Clear Reference if task own reference
else if not CAS(Result, ThreadReference, Result.Next, 0, chain) then
goto TryAgain;
end; //with chain
{$ELSE ~OTL_HaveCmpx16b}
Result := chain.PData;
chain.PData := Result^.Next;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedStack.PopLink }
function TOmniBaseBoundedStack.Push(const value): boolean;
var
linkedData: POmniLinkedData;
begin
Acquire;
try
linkedData := PopLink(obsRecycleChainP^);
Result := assigned(linkedData);
if not Result then
Exit;
Move(value, linkedData.Data, ElementSize);
PushLink(linkedData, obsPublicChainP^);
finally Release; end;
end; { TOmniBaseBoundedStack.Push }
class procedure TOmniBaseBoundedStack.PushLink(const link: POmniLinkedData; var chain: TReferencedPtr);
var
PMemData : pointer;
TaskCounter: NativeInt;
begin
{$IFDEF OTL_HaveCmpx16b}
with chain do begin
for TaskCounter := 0 to obsTaskPushLoops do
if (Reference AND 1 = 0) then
break;
repeat
PMemData := PData;
link.Next := PMemData;
until TInterlockedEx.CAS(PMemData, link, PData);
end;
{$ELSE ~OTL_HaveCmpx16b}
link.Next := chain.PData;
chain.PData := link;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedStack.PushLink }
{ TOmniBoundedStack }
constructor TOmniBoundedStack.Create(numElements, elementSize: integer; partlyEmptyLoadFactor,
almostFullLoadFactor: real);
begin
inherited Create;
Initialize(numElements, elementSize);
osContainerSubject := TOmniContainerSubject.Create;
osInStackCount.Value := 0;
osPartlyEmptyCount := Round(numElements * partlyEmptyLoadFactor);
if osPartlyEmptyCount >= numElements then
osPartlyEmptyCount := numElements - 1;
osAlmostFullCount := Round(numElements * almostFullLoadFactor);
if osAlmostFullCount >= numElements then
osAlmostFullCount := numElements - 1;
end; { TOmniBoundedStack.Create }
destructor TOmniBoundedStack.Destroy;
begin
FreeAndNil(osContainerSubject);
inherited;
end; { TOmniBoundedStack.Destroy }
function TOmniBoundedStack.Pop(var value): boolean;
var
countAfter: integer;
begin
Result := inherited Pop(value);
if Result then begin
countAfter := osInStackCount.Decrement;
ContainerSubject.Notify(coiNotifyOnAllRemoves);
if countAfter <= osPartlyEmptyCount then
ContainerSubject.NotifyOnce(coiNotifyOnPartlyEmpty);
end;
end; { TOmniBoundedStack.Pop }
function TOmniBoundedStack.Push(const value): boolean;
var
countAfter: integer;
begin
Result := inherited Push(value);
if Result then begin
countAfter := osInStackCount.Increment;
ContainerSubject.Notify(coiNotifyOnAllInserts);
if countAfter >= osAlmostFullCount then
ContainerSubject.NotifyOnce(coiNotifyOnAlmostFull);
end;
end; { TOmniBoundedStack.Push }
{ TOmniBaseBoundedQueue }
constructor TOmniBaseBoundedQueue.Create;
begin
inherited Create;
{$IFNDEF OTL_HaveCmpx16b}
obqLock := CreateOmniCriticalSection;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedQueue.Create }
destructor TOmniBaseBoundedQueue.Destroy;
begin
FreeMem(obqDataBuffer);
FreeMem(obqPublicRingMem);
FreeMem(obqRecycleRingMem);
inherited;
end; { TOmniBaseBoundedQueue.Destroy }
procedure TOmniBaseBoundedQueue.Acquire; //inline
begin
{$IFNDEF OTL_HaveCmpx16b}
obqLock.Acquire;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedQueue.Acquire }
procedure TOmniBaseBoundedQueue.Release; //inline
begin
{$IFNDEF OTL_HaveCmpx16b}
obqLock.Release;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedQueue.Release }
function TOmniBaseBoundedQueue.Dequeue(var value): boolean;
var
Data: pointer;
begin
Acquire;
try
Data := RemoveLink(obqPublicRingBuffer);
Result := assigned(Data);
if not Result then
Exit;
Move(Data^, value, ElementSize);
InsertLink(Data, obqRecycleRingBuffer);
finally Release; end;
end; { TOmniBaseBoundedQueue.Dequeue }
procedure TOmniBaseBoundedQueue.Empty;
var
Data: pointer;
begin
Acquire;
try
repeat
Data := RemoveLink(obqPublicRingBuffer);
if assigned(Data) then
InsertLink(Data, obqRecycleRingBuffer)
else
break;
until false;
finally Release; end;
end; { TOmniBaseBoundedQueue.Empty }
function TOmniBaseBoundedQueue.Enqueue(const value): boolean;
var
Data: pointer;
begin
Acquire;
try
Data := RemoveLink(obqRecycleRingBuffer);
Result := assigned(Data);
if not Result then
Exit;
Move(value, Data^, ElementSize);
InsertLink(Data, obqPublicRingBuffer);
finally Release; end;
end; { TOmniBaseBoundedQueue.Enqueue }
procedure TOmniBaseBoundedQueue.Initialize(numElements, elementSize: integer);
var
dataBuffer : pointer;
n : integer;
ringBufferSize : cardinal;
roundedElementSize: integer;
begin
Assert(SizeOf(NativeInt) = SizeOf(pointer));
Assert(numElements > 0);
Assert(elementSize > 0);
obqNumElements := numElements;
obqElementSize := elementSize;
// calculate element size, round up to next aligned value
roundedElementSize := (elementSize + SizeOf(pointer) - 1) AND NOT (SizeOf(pointer) - 1);
// allocate obqDataBuffer
FreeMem(obqDataBuffer);
GetMem(obqDataBuffer, roundedElementSize * numElements + roundedElementSize + CASAlignment);
dataBuffer := RoundUpTo(obqDataBuffer, CASAlignment);
// allocate RingBuffers
ringBufferSize := SizeOf(TReferencedPtr) * (numElements + 1) +
SizeOf(TOmniRingBuffer) - SizeOf(TReferencedPtrBuffer);
FreeMem(obqPublicRingMem);
obqPublicRingMem := AllocMem(ringBufferSize + SizeOf(pointer) * 2);
obqPublicRingBuffer := RoundUpTo(obqPublicRingMem, SizeOf(pointer) * 2);
Assert(NativeInt(obqPublicRingBuffer) mod (SizeOf(pointer) * 2) = 0,
Format('TOmniBaseContainer: obcPublicRingBuffer is not %d-aligned', [SizeOf(pointer) * 2]));
FreeMem(obqRecycleRingMem);
obqRecycleRingMem := AllocMem(ringBufferSize + SizeOf(pointer) * 2);
obqRecycleRingBuffer := RoundUpTo(obqRecycleRingMem, SizeOf(pointer) * 2);
Assert(NativeInt(obqRecycleRingBuffer) mod (SizeOf(pointer) * 2) = 0,
Format('TOmniBaseContainer: obcRecycleRingBuffer is not %d-aligned', [SizeOf(pointer) * 2]));
// set obqPublicRingBuffer head
obqPublicRingBuffer.FirstIn.PData := @obqPublicRingBuffer.Buffer[0];
obqPublicRingBuffer.LastIn.PData := @obqPublicRingBuffer.Buffer[0];
obqPublicRingBuffer.StartBuffer := @obqPublicRingBuffer.Buffer[0];
obqPublicRingBuffer.EndBuffer := @obqPublicRingBuffer.Buffer[numElements];
// set obqRecycleRingBuffer head
obqRecycleRingBuffer.FirstIn.PData := @obqRecycleRingBuffer.Buffer[0];
obqRecycleRingBuffer.LastIn.PData := @obqRecycleRingBuffer.Buffer[numElements];
obqRecycleRingBuffer.StartBuffer := @obqRecycleRingBuffer.Buffer[0];
obqRecycleRingBuffer.EndBuffer := @obqRecycleRingBuffer.Buffer[numElements];
// format obqRecycleRingBuffer
for n := 0 to numElements do
obqRecycleRingBuffer.Buffer[n].PData := pointer(NativeInt(dataBuffer) + NativeInt(n * roundedElementSize));
MeasureExecutionTimes;
end; { TOmniBaseBoundedQueue.Initialize }
class procedure TOmniBaseBoundedQueue.InsertLink(const data: pointer; const ringBuffer:
POmniRingBuffer);
//FIFO buffer logic
//Insert link to queue model with idle/busy status bit
var
AtStartReference: NativeInt;
CurrentLastIn : PReferencedPtr;
CurrentReference: NativeInt;
NewLastIn : PReferencedPtr;
TaskCounter : NativeInt;
ThreadReference : NativeInt;
label
TryAgain;
begin
{$IFDEF OTL_HaveCmpx16b}
ThreadReference := OtlSync.GetThreadId + 1; //Reference.bit0 := 1
with ringBuffer^ do begin
TryAgain:
TaskCounter := obqTaskInsertLoops;
AtStartReference := LastIn.Reference OR 1; //Reference.bit0 := 1
repeat
CurrentReference := LastIn.Reference;
Dec(TaskCounter);
until (TaskCounter = 0) or (CurrentReference AND 1 = 0);
if ((CurrentReference AND 1 <> 0) and (AtStartReference <> CurrentReference))
or (not TInterlockedEx.CAS(CurrentReference, ThreadReference, LastIn.Reference))
then
goto TryAgain;
//Reference is set...
CurrentLastIn := LastIn.PData;
TInterlockedEx.CAS(CurrentLastIn.Reference, ThreadReference, CurrentLastIn.Reference);
if (ThreadReference <> LastIn.Reference) or
(not CAS(CurrentLastIn.PData, ThreadReference, data, ThreadReference, CurrentLastIn^))
then
goto TryAgain; //Calculate ringBuffer next LastIn address
NewLastIn := pointer(NativeInt(CurrentLastIn) + SizeOf(TReferencedPtr));
if NativeInt(NewLastIn) > NativeInt(EndBuffer) then
NewLastIn := StartBuffer;
//Try to exchange and clear Reference if task own reference
if not CAS(CurrentLastIn, ThreadReference, NewLastIn, 0, LastIn) then
goto TryAgain;
end;
{$ELSE ~OTL_HaveCmpx16b}
CurrentLastIn := ringBuffer^.LastIn.PData;
CurrentLastIn^.PData := data;
NewLastIn := pointer(NativeInt(CurrentLastIn) + SizeOf(TReferencedPtr));
if NativeInt(NewLastIn) > NativeInt(ringBuffer^.EndBuffer) then
NewLastIn := ringBuffer^.StartBuffer;
ringBuffer^.LastIn.PData := NewLastIn;
{$ENDIF ~OTL_HaveCmpx16b}
end; { TOmniBaseBoundedQueue.InsertLink }
function TOmniBaseBoundedQueue.IsEmpty: boolean;
begin
Result := (obqPublicRingBuffer.FirstIn.PData = obqPublicRingBuffer.LastIn.PData);
end; { TOmniBaseBoundedQueue.IsEmpty }
function TOmniBaseBoundedQueue.IsFull: boolean;
var
NewLastIn: pointer;
begin
Acquire;
try
NewLastIn := pointer(NativeInt(obqPublicRingBuffer.LastIn.PData) + SizeOf(TReferencedPtr));
if NativeInt(NewLastIn) > NativeInt(obqPublicRingBuffer.EndBuffer) then
NewLastIn := obqPublicRingBuffer.StartBuffer;
result := (NativeInt(NewLastIn) = NativeInt(obqPublicRingBuffer.LastIn.PData)) or
(obqRecycleRingBuffer.FirstIn.PData = obqRecycleRingBuffer.LastIn.PData);
finally Release; end;
end; { TOmniBaseBoundedQueue.IsFull }
procedure TOmniBaseBoundedQueue.MeasureExecutionTimes;
const
NumOfSamples = 10;
var
TimeTestField: array [0..1] of array [1..NumOfSamples] of int64;
function GetMinAndClear(routine, count: cardinal): int64;
var
m: cardinal;
n: integer;
x: integer;
begin
Result := 0;
for m := 1 to count do begin
x:= 1;
for n:= 2 to NumOfSamples do
if TimeTestField[routine, n] < TimeTestField[routine, x] then
x := n;
Inc(Result, TimeTestField[routine, x]);
TimeTestField[routine, x] := MaxLongInt;
end;
end; { GetMinAndClear }
var
{$IFDEF MSWINDOWS}
affinity : string;
{$ENDIF MSWINDOWS}
currElement: pointer;
n : integer;
begin { TOmniBaseBoundedQueue.MeasureExecutionTimes }