File: lazcollections.pas

package info (click to toggle)
lazarus 4.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 275,760 kB
  • sloc: pascal: 2,341,904; xml: 509,420; makefile: 348,726; cpp: 93,608; sh: 3,387; java: 609; perl: 297; sql: 222; ansic: 137
file content (537 lines) | stat: -rw-r--r-- 12,911 bytes parent folder | download | duplicates (2)
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
{
 *****************************************************************************
  This file is part of LazUtils.

  See the file COPYING.modifiedLGPL.txt, included in this distribution,
  for details about the license.
 *****************************************************************************
}
unit LazCollections;

{$mode objfpc}{$H+}
{$ModeSwitch advancedrecords}

interface

uses
  sysutils, math, syncobjs,
  // LazUtils
  LazSysUtils;

type

  PPRTLEvent = ^PRTLEvent;

  { TWaitableSection }

  TWaitableSection = record
  strict private
    FEventPtr: PPRTLEvent;
    procedure WaitForLeave(AnEventCache: PPRTLEvent);
  private const
    SECTION_ENTERED_INDICATOR = Pointer(1);
  public
    function  GetCachedOrNewEvent(AnEventCache: PPRTLEvent): PRTLEvent; inline;
    procedure FreeOrCacheEvent(AnEventCache: PPRTLEvent; AnEvent: PRTLEvent); inline;
    function EnterOrWait(AnEventCache: PPRTLEvent = nil): Boolean; inline;
    procedure Leave;  // if enter returned true
  end;

  { TLazMonitor }

  TLazMonitor = class(TCriticalSection)
  private
    FSpinCount: integer;
    class var FDefaultSpinCount: integer;
    class function GetDefaultSpinCount: integer; static;
    class procedure SetDefaultSpinCount(AValue: integer); static;
    function GetSpinCount: integer;
    procedure SetSpinCount(AValue: integer);
  public
    constructor create;
    procedure Acquire; override;
    property SpinCount: integer read GetSpinCount write SetSpinCount;
    class property DefaultSpinCount: integer read GetDefaultSpinCount write SetDefaultSpinCount;
  end;

  { TLazFifoQueue }

  generic TLazFifoQueue<T> = class
  private
    FList: array of T;
    FQueueSize: integer;
  protected
    FTotalItemsPopped: QWord;
    FTotalItemsPushed: QWord;
    function GetIsEmpty: Boolean; virtual;
    function GetIsFull: Boolean; virtual;
  public
    constructor create(AQueueDepth: Integer = 10);
    procedure Grow(ADelta: integer);
    function PushItem(const AItem: T): Boolean; virtual;
    function PopItem(out AItem: T): Boolean; virtual;
    property QueueSize: integer read FQueueSize;
    property TotalItemsPopped: QWord read FTotalItemsPopped;
    property TotalItemsPushed: QWord read FTotalItemsPushed;
    property IsEmpty: Boolean read GetIsEmpty;
    property IsFull: Boolean read GetIsFull;
  end;

  { TLazThreadedQueue }

  generic TLazThreadedQueue<T> = class
  protected
  type
    TLazTypedFifoQueue = specialize TLazFifoQueue<T>;
  private
    FMonitor: TLazMonitor;
    FFifoQueue: TLazTypedFifoQueue;
    FPushTimeout: Cardinal;
    FPopTimeout: Cardinal;
    FHasRoomEvent: PRTLEvent;
    FHasItemEvent: PRTLEvent;
    FShutDown: boolean;
    function GetQueueSize: integer; inline;
    function GetTotalItemsPopped: QWord; inline;
    function GetTotalItemsPushed: QWord; inline;
    function TryPushItem(const AItem: T): boolean; inline;
    function TryPopItem(out AItem: T): boolean; inline;
  protected
    function TryPushItemUnprotected(const AItem: T): boolean;
    function TryPopItemUnprotected(out AItem: T): boolean;
    procedure Lock;
    procedure Unlock;
    function CreateFifoQueue(AQueueDepth: Integer): TLazTypedFifoQueue; virtual;
    property FifoQueue: TLazTypedFifoQueue read FFifoQueue;
  public
    constructor create(AQueueDepth: Integer = 10; PushTimeout: cardinal = INFINITE; PopTimeout: cardinal = INFINITE);
    destructor Destroy; override;
    procedure Grow(ADelta: integer);
    function PushItem(const AItem: T): TWaitResult;
    function PopItem(out AItem: T): TWaitResult;
    function PopItemTimeout(out AItem: T; Timeout: cardinal): TWaitResult;
    procedure DoShutDown;
    property QueueSize: integer read GetQueueSize;
    property TotalItemsPopped: QWord read GetTotalItemsPopped;
    property TotalItemsPushed: QWord read GetTotalItemsPushed;
    property ShutDown: boolean read FShutDown;
  end;


implementation

{ TWaitableSection }

procedure TWaitableSection.WaitForLeave(AnEventCache: PPRTLEvent);
var
  Evnt: PRTLEvent;
  ExistingEvntPtr: PPRTLEvent;
begin
  Evnt := GetCachedOrNewEvent(AnEventCache);
  ExistingEvntPtr := InterlockedExchange(FEventPtr, @Evnt);

  if ExistingEvntPtr = nil then begin
    // section has been left already
    ExistingEvntPtr := InterlockedExchange(FEventPtr, nil);
    if ExistingEvntPtr <> @Evnt then begin
      // An other thread has our event, and is waitig
      RTLEventSetEvent(ExistingEvntPtr^);
      RTLEventWaitFor(Evnt);
    end;
    FreeOrCacheEvent(AnEventCache, Evnt);
    exit;
  end;

  // wait for our signal
  RTLEventWaitFor(Evnt);

  if ExistingEvntPtr <> SECTION_ENTERED_INDICATOR then
    RTLEventSetEvent(ExistingEvntPtr^);
end;

function TWaitableSection.GetCachedOrNewEvent(AnEventCache: PPRTLEvent
  ): PRTLEvent;
begin
  Result := nil;
  if AnEventCache <> nil then
    Result := InterlockedExchange(AnEventCache^, nil);
  if Result = nil then
    Result := RTLEventCreate
  else
    RTLEventResetEvent(Result);
end;

procedure TWaitableSection.FreeOrCacheEvent(AnEventCache: PPRTLEvent;
  AnEvent: PRTLEvent);
begin
  if AnEventCache <> nil then
    AnEvent := InterlockedExchange(AnEventCache^, AnEvent);
  if AnEvent <> nil then
    RTLEventDestroy(AnEvent);
end;

function TWaitableSection.EnterOrWait(AnEventCache: PPRTLEvent): Boolean;
var
  ExistingEvntPtr: PPRTLEvent;
begin
  ExistingEvntPtr := InterlockedCompareExchange(FEventPtr, SECTION_ENTERED_INDICATOR, nil);
  Result := ExistingEvntPtr = nil;
  if Result then
    exit;

  WaitForLeave(AnEventCache);
end;

procedure TWaitableSection.Leave;
var
  ExistingEvntPtr: PPRTLEvent;
begin
  ExistingEvntPtr := InterlockedExchange(FEventPtr, nil);
  assert(ExistingEvntPtr <> nil);

  if ExistingEvntPtr <> SECTION_ENTERED_INDICATOR then
    RTLEventSetEvent(ExistingEvntPtr^);
end;

{ TLazMonitor }

function TLazMonitor.GetSpinCount: integer;
begin
  result := FSpinCount;
end;

procedure TLazMonitor.SetSpinCount(AValue: integer);
begin
  InterLockedExchange(FSpinCount, AValue);
end;

class function TLazMonitor.GetDefaultSpinCount: integer; static;
begin
  result := FDefaultSpinCount;
end;

class procedure TLazMonitor.SetDefaultSpinCount(AValue: integer); static;
begin
  InterLockedExchange(FDefaultSpinCount, AValue);
end;

constructor TLazMonitor.create;
begin
  FSpinCount:=FDefaultSpinCount;
  inherited;
end;

procedure TLazMonitor.Acquire;
const
  YieldTreshold = 10;
  Sleep1Treshold = 20;
  Sleep0Treshold = 5;
var
  i,j: integer;
  Waitcount: integer;
  ASpinCount: integer;
  Sp: integer;
begin
  ASpinCount:=FSpinCount;
  for Sp := 0 to ASpinCount-1 do
  begin
    Waitcount:=1;
    for i := 0 to YieldTreshold-1 do
      begin
      if TryEnter then
        Exit;
      {$PUSH}
      {$OPTIMIZATION OFF}
      for j := 0 to Waitcount-1 do
        begin
        end;
      {$POP}
      Waitcount:=Waitcount*2;
      end;

    for i := 0 to Sleep1Treshold-1 do
      begin
      if TryEnter then
        Exit;
      sleep(1);
      end;

    for i := 0 to Sleep0Treshold do
      begin
      if TryEnter then
        Exit;
      sleep(0);
      end;
  end;

  inherited Acquire;
end;

{ TLazFifoQueue }

function TLazFifoQueue.GetIsEmpty: Boolean;
begin
  result := FTotalItemsPushed = FTotalItemsPopped;
end;

function TLazFifoQueue.GetIsFull: Boolean;
begin
  result := FTotalItemsPushed - FTotalItemsPopped = FQueueSize;
end;

constructor TLazFifoQueue.create(AQueueDepth: Integer);
begin
  Grow(AQueueDepth);
end;

procedure TLazFifoQueue.Grow(ADelta: integer);
var
  NewList: array of T;
  c: Integer;
  i: QWord;
begin
  c:=Max(FQueueSize + ADelta, Integer(FTotalItemsPushed - FTotalItemsPopped));
  setlength(NewList{%H-}, c);
  i:=FTotalItemsPopped;
  while i < FTotalItemsPushed do begin
    NewList[i mod c] := FList[i mod FQueueSize];
    inc(i);
  end;

  FList := NewList;
  FQueueSize:=c;
end;

function TLazFifoQueue.PushItem(const AItem: T): Boolean;
begin
  result := FTotalItemsPushed-FTotalItemsPopped<FQueueSize;
  if result then
    begin
    FList[FTotalItemsPushed mod FQueueSize]:=AItem;
    inc(FTotalItemsPushed);
    end;
end;

function TLazFifoQueue.PopItem(out AItem: T): Boolean;
begin
  result := FTotalItemsPushed>FTotalItemsPopped;
  if result then
    begin
    AItem := FList[FTotalItemsPopped mod FQueueSize];
    inc(FTotalItemsPopped);
    end;
end;

{ TThreadedQueue }

function TLazThreadedQueue.TryPushItem(const AItem: T): boolean;
begin
  FMonitor.Enter;
  try
    result := TryPushItemUnprotected(AItem);
  finally
    FMonitor.Leave;
  end;
end;

function TLazThreadedQueue.GetQueueSize: integer;
begin
  Result := FFifoQueue.QueueSize;
end;

function TLazThreadedQueue.GetTotalItemsPopped: QWord;
begin
  Result := FFifoQueue.TotalItemsPopped;
end;

function TLazThreadedQueue.GetTotalItemsPushed: QWord;
begin
  Result := FFifoQueue.TotalItemsPushed;
end;

function TLazThreadedQueue.TryPopItem(out AItem: T): boolean;
begin
  FMonitor.Enter;
  try
    result := TryPopItemUnprotected(AItem);
  finally
    FMonitor.Leave;
  end;
end;

function TLazThreadedQueue.TryPushItemUnprotected(const AItem: T): boolean;
begin
  result := FFifoQueue.PushItem(AItem);
  if result then
    RTLeventSetEvent(FHasItemEvent);

  RTLeventResetEvent(FHasRoomEvent);
  if ShutDown or not FFifoQueue.IsFull then
    RTLeventSetEvent(FHasRoomEvent);
end;

function TLazThreadedQueue.TryPopItemUnprotected(out AItem: T): boolean;
begin
  result := FFifoQueue.PopItem(AItem);
  if result then
    RTLeventSetEvent(FHasRoomEvent);

  RTLeventResetEvent(FHasItemEvent);
  if ShutDown or not FFifoQueue.IsEmpty then
    RTLeventSetEvent(FHasItemEvent);
end;

procedure TLazThreadedQueue.Lock;
begin
  FMonitor.Enter;
end;

procedure TLazThreadedQueue.Unlock;
begin
  FMonitor.Leave;
end;

function TLazThreadedQueue.CreateFifoQueue(AQueueDepth: Integer
  ): TLazTypedFifoQueue;
begin
  result := TLazTypedFifoQueue.create(AQueueDepth);
end;

constructor TLazThreadedQueue.create(AQueueDepth: Integer; PushTimeout: cardinal; PopTimeout: cardinal);
begin
  FMonitor:=TLazMonitor.create;
  FFifoQueue := CreateFifoQueue(AQueueDepth);
  Grow(AQueueDepth);
  FHasRoomEvent:=RTLEventCreate;
  RTLeventSetEvent(FHasRoomEvent);
  FHasItemEvent:=RTLEventCreate;
  FPushTimeout:=PushTimeout;
  FPopTimeout:=PopTimeout;
end;

destructor TLazThreadedQueue.Destroy;
begin
  DoShutDown;
  RTLeventdestroy(FHasRoomEvent);
  RTLeventdestroy(FHasItemEvent);
  FMonitor.Free;
  FFifoQueue.Free;
  inherited Destroy;
end;

procedure TLazThreadedQueue.Grow(ADelta: integer);
begin
  FMonitor.Enter;
  try
    FFifoQueue.Grow(ADelta);
  finally
    FMonitor.Leave;
  end;
end;

function TLazThreadedQueue.PushItem(const AItem: T): TWaitResult;
var
  tc, ltc: int64;
begin
  if (FPushTimeout<>INFINITE) and (FPushTimeout<>0) then
    begin
    tc := GetTickCount64;
    ltc := 0;
    end;
  if TryPushItem(AItem) then
    result := wrSignaled
  else
    begin
    repeat
    if FPushTimeout=0 then
      begin
      result := wrTimeout;
      Exit;
      end
    else if FPushTimeout=INFINITE then
      RTLeventWaitFor(FHasRoomEvent)
    else
      begin
      RTLeventWaitFor(FHasRoomEvent, FPushTimeout - ltc);
    ltc := GetTickCount64-tc;
      if ltc > FPushTimeout then
        begin
        result := wrTimeout;
        Exit;
        end;
      end;
    if FShutDown then
      begin
      RTLeventResetEvent(FHasRoomEvent);
      RTLeventResetEvent(FHasItemEvent);
      RTLeventSetEvent(FHasRoomEvent);
      RTLeventSetEvent(FHasItemEvent);
      result := wrAbandoned;
      exit;
      end;
    until TryPushItem(AItem);
    result := wrSignaled;
    end;
end;

function TLazThreadedQueue.PopItem(out AItem: T): TWaitResult;
begin
  result := PopItemTimeout(AItem, FPopTimeout);
end;

function TLazThreadedQueue.PopItemTimeout(out AItem: T; Timeout: cardinal): TWaitResult;
var
  tc, ltc: int64;
begin
  if (Timeout<>INFINITE) and (Timeout<>0) then
    begin
    tc := GetTickCount64;
    ltc := 0;
    end;
  if TryPopItem(AItem) then
    result := wrSignaled
  else
    begin
    if Timeout=0 then
      begin
      result := wrTimeout;
      Exit;
      end;
    repeat
    if Timeout=INFINITE then
      RTLeventWaitFor(FHasItemEvent)
    else
      begin
      RTLeventWaitFor(FHasItemEvent, Timeout - ltc);
      ltc := GetTickCount64-tc;
      if ltc > Timeout then
        begin
        result := wrTimeout;
        Exit;
        end;
      end;
    if FShutDown then
      begin
      RTLeventResetEvent(FHasRoomEvent);
      RTLeventResetEvent(FHasItemEvent);
      RTLeventSetEvent(FHasRoomEvent);
      RTLeventSetEvent(FHasItemEvent);
      result := wrAbandoned;
      exit;
      end;
    until TryPopItem(AItem);
    result := wrSignaled;
    end;
end;

procedure TLazThreadedQueue.DoShutDown;
begin
  FShutDown:=true;
  RTLeventSetEvent(FHasRoomEvent);
  RTLeventSetEvent(FHasItemEvent);
end;

initialization
  TLazMonitor.DefaultSpinCount:=3;
end.