-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
LinSyncObjs.pas
4461 lines (3855 loc) · 156 KB
/
LinSyncObjs.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
{-------------------------------------------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
-------------------------------------------------------------------------------}
{===============================================================================
LinSyncObjs
This library provides a set of classes encapsulating synchronization
objects available in pthreads library for Linux operating system.
It also implements some new and derived synchronization primitives that
are not directly provided by pthreads along with a limited form of waiting
for multiple synchronization objects (in this case waiting for multiple
events).
All provided objects, except for critical section, can be created either
as thread-shared (can be used for synchronization between threads of a
single process) or as process-shared (synchronization between any threads
within the system, even in different processes).
Process-shared objects reside in a shared memory and are accessed using
their names (such object must have a non-empty name). All object types
share the same name space, so it is not possible for multiple objects of
different types to have the same name. Names are case sensitive.
NOTE - the events and multi-wait were tested, but there may still be some
problems. Use them with caution and if you find any bugs, please
report them.
Version 1.1 (2024-05-15)
Last change 2024-09-09
©2022-2024 František Milt
Contacts:
František Milt: [email protected]
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.LinSyncObjs
Dependencies:
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
* AuxExceptions - github.com/TheLazyTomcat/Lib.AuxExceptions
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
BitOps - github.com/TheLazyTomcat/Lib.BitOps
BitVector - github.com/TheLazyTomcat/Lib.BitVector
InterlockedOps - github.com/TheLazyTomcat/Lib.InterlockedOps
NamedSharedItems - github.com/TheLazyTomcat/Lib.NamedSharedItems
SharedMemoryStream - github.com/TheLazyTomcat/Lib.SharedMemoryStream
SimpleFutex - github.com/TheLazyTomcat/Lib.SimpleFutex
Library AuxExceptions is required only when rebasing local exception classes
(see symbol LinSyncObjs_UseAuxExceptions for details).
Library AuxExceptions might also be required as an indirect dependency.
Indirect dependencies:
BasicUIM - github.com/TheLazyTomcat/Lib.BasicUIM
BinaryStreamingLite - github.com/TheLazyTomcat/Lib.BinaryStreamingLite
HashBase - github.com/TheLazyTomcat/Lib.HashBase
SHA1 - github.com/TheLazyTomcat/Lib.SHA1
SimpleCPUID - github.com/TheLazyTomcat/Lib.SimpleCPUID
StaticMemoryStream - github.com/TheLazyTomcat/Lib.StaticMemoryStream
StrRect - github.com/TheLazyTomcat/Lib.StrRect
UInt64Utils - github.com/TheLazyTomcat/Lib.UInt64Utils
WinFileInfo - github.com/TheLazyTomcat/Lib.WinFileInfo
===============================================================================}
unit LinSyncObjs;
{
LinSyncObjs_UseAuxExceptions
If you want library-specific exceptions to be based on more advanced classes
provided by AuxExceptions library instead of basic Exception class, and don't
want to or cannot change code in this unit, you can define global symbol
LinSyncObjs_UseAuxExceptions to achieve this.
}
{$IF Defined(LinSyncObjs_UseAuxExceptions)}
{$DEFINE UseAuxExceptions}
{$IFEND}
//------------------------------------------------------------------------------
{$IF Defined(LINUX) and Defined(FPC)}
{$DEFINE Linux}
{$ELSE}
{$MESSAGE FATAL 'Unsupported operating system.'}
{$IFEND}
{$IFDEF FPC}
{$MODE ObjFPC}
{$MODESWITCH DuplicateLocals+}
{$DEFINE FPC_DisableWarns}
{$MACRO ON}
{$ENDIF}
{$H+}
{$IFOPT Q+}
{$DEFINE OverflowChecks}
{$ENDIF}
interface
uses
SysUtils, BaseUnix, PThreads,
AuxTypes, AuxClasses, BitVector, SimpleFutex, SharedMemoryStream,
NamedSharedItems{$IFDEF UseAuxExceptions}, AuxExceptions{$ENDIF};
{===============================================================================
Library-specific exceptions
===============================================================================}
type
ELSOException = class({$IFDEF UseAuxExceptions}EAEGeneralException{$ELSE}Exception{$ENDIF});
ELSOSysInitError = class(ELSOException);
ELSOSysFinalError = class(ELSOException);
ELSOSysOpError = class(ELSOException);
ELSOOpenError = class(ELSOException);
ELSOInvalidLockType = class(ELSOException);
ELSOInvalidObject = class(ELSOException);
{===============================================================================
--------------------------------------------------------------------------------
TCriticalSection
--------------------------------------------------------------------------------
===============================================================================}
{
To use the TCriticalSection object, create one instance and then pass this
one instance to other threads that need to be synchronized.
Make sure to only free the object once.
You can also set the property FreeOnRelease to true (by default false) and
then use the build-in reference counting - call method Acquire for each
thread using the object (including the one that created it) and method
Release every time a thread will stop using it. When reference count reaches
zero in a call to Release, the object will be automatically freed within that
call.
}
{===============================================================================
TCriticalSection - class declaration
===============================================================================}
type
TCriticalSection = class(TCustomRefCountedObject)
protected
fMutex: pthread_mutex_t;
fLockComplete: Boolean;
procedure Initialize; virtual;
procedure Finalize; virtual;
public
constructor Create;
destructor Destroy; override;
Function TryEnter: Boolean; virtual;
procedure Enter; virtual;
procedure Leave; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
TLinSyncObject
--------------------------------------------------------------------------------
===============================================================================}
{
To properly use linux synchronization object based on TLinSyncObject class
(all that are currently provided), create an instance and use this one
instance only in a thread where it was created.
To access the object in other threads of the same process, create a new
instance using DuplicateFrom constructor, passing the progenitor instance or
any duplicate instance created previously from it as a source.
You can also use Open or Create constructors when the object is created as
process-shared.
It is possible and permissible to use the same instance in multiple threads
of single process, but this practice is not recommended as the object fields
are not protected against concurrent access (affects eg. LastError property).
To access the object in a different process (object must be created as
process-shared), use Open or Create constructors using the same name as was
used for the first instance. When opening process-shared object in the same
process where it was created or already opened, you can use DuplicateFrom
constructor.
Most public functions of classes derived from TLinSyncObject that are
operating on the object state are provided in two versions - as strict and
non-strict.
Unless noted otherwise, the strict functions will raise an ELSOSysOpError
exception when the internal operation fails. Non-strict functions indicate
success or failure via their result (true = success, false = failure).
Value stored in LastError property is undefined after a call to any strict
function.
When non-strict function succeeds, the value of LastError is also undefined.
When it fails, the LastError will contain a code of system error that caused
the function to fail.
Non-strict function beginning with a "Try" (eg. TryLock) might return false
even when it technically succeeded in its operation (the object was already
locked). In that case, LastError is explicitly set to 0.
Timed functions will never raise an exception, all errors are indicated by
returning wrError result and error code is stored in LastError. Value of
LastError is undefined for results other than wrError.
}
{===============================================================================
TLinSyncObject - public types and constants
===============================================================================}
const
INFINITE = UInt32($FFFFFFFF); // infinite timeout
type
TLSOSharedUserData = packed array[0..31] of Byte;
PLSOSharedUserData = ^TLSOSharedUserData;
type
TLSOWaitResult = (wrSignaled,wrAbandoned,wrTimeout,wrError);
// TLSOLockType is used only internally
TLSOLockType = (ltInvalid,ltSpinLock,ltStatelessEvent,ltSimpleManualEvent,
ltSimpleAutoEvent,ltEvent,ltMutex,ltSemaphore,ltRWLock,
ltCondVar,ltCondVarEx,ltBarrier);
{===============================================================================
TLinSyncObject - class declaration
===============================================================================}
type
TLinSyncObject = class(TCustomObject)
protected
fLastError: Integer;
fName: String;
fProcessShared: Boolean;
fNamedSharedItem: TNamedSharedItem; // unused in thread-shared mode
fSharedData: Pointer;
fLockPtr: Pointer;
fLockPrepComplete: Boolean;
// getters, setters
Function GetSharedUserDataPtr: PLSOSharedUserData; virtual;
Function GetSharedUserData: TLSOSharedUserData; virtual;
procedure SetSharedUserData(Value: TLSOSharedUserData); virtual;
// lock management methods
class Function GetLockType: TLSOLockType; virtual; abstract;
procedure CheckAndSetLockType; virtual;
procedure ResolveLockPtr; virtual; abstract;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); virtual;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); virtual; abstract;
// object initialization/finalization
procedure Initialize(const Name: String; InitializingData: PtrUInt); overload; virtual;
// following overload can be used only to open existing process-shared objects
procedure Initialize(const Name: String); overload; virtual;
procedure Finalize; virtual;
public
constructor ProtectedCreate(const Name: String; InitializingData: PtrUInt); virtual;
constructor Create(const Name: String); overload; virtual;
constructor Create; overload; virtual;
constructor Open(const Name: String); virtual;
constructor DuplicateFrom(SourceObject: TLinSyncObject); virtual;
destructor Destroy; override;
// properties
property LastError: Integer read fLastError;
property Name: String read fName;
property ProcessShared: Boolean read fProcessShared;
property SharedUserDataPtr: PLSOSharedUserData read GetSharedUserDataPtr;
property SharedUserData: TLSOSharedUserData read GetSharedUserData write SetSharedUserData;
end;
{===============================================================================
--------------------------------------------------------------------------------
TImplementorLinSynObject
--------------------------------------------------------------------------------
===============================================================================}
{
TImplementorLinSyncObject is a base class for objects creating a distinct
synchronization primitive that is not a simple wrapper for pthread primitives.
}
{===============================================================================
TImplementorLinSynObject - class declaration
===============================================================================}
type
TImplementorLinSyncObject = class(TLinSyncObject);
{===============================================================================
--------------------------------------------------------------------------------
Events
--------------------------------------------------------------------------------
===============================================================================}
type
TLSOSimpleEvent = record
Event: TFutexWord;
end;
PLSOSimpleEvent = ^TLSOSimpleEvent;
{===============================================================================
--------------------------------------------------------------------------------
TStatelessEvent
--------------------------------------------------------------------------------
===============================================================================}
{
Stateless event does not have any internal state (obviously), so it cannot be
locked (non-signaled) or unlocked (signaled).
When a thread enters waiting on this type of event, it is not waiting for the
event to become unlocked (signaled), it waits for some other thread to call
method Signal or SignalStrict. When Signal* method is called, all waiting
threads are released from waiting. Threads entering wait after this call will
again block until next call to Signal*.
}
{===============================================================================
TStatelessEvent - flat interface declaration
===============================================================================}
Function event_stateless_init(event: PLSOSimpleEvent): cInt;
Function event_stateless_destroy(event: PLSOSimpleEvent): cInt;
Function event_stateless_signal(event: PLSOSimpleEvent): cInt;
Function event_stateless_wait(event: PLSOSimpleEvent): cInt;
Function event_stateless_timedwait(event: PLSOSimpleEvent; timeout: cUnsigned): cInt;
{===============================================================================
TStatelessEvent - class declaration
===============================================================================}
type
TStatelessEvent = class(TImplementorLinSyncObject)
protected
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
procedure SignalStrict; virtual;
Function Signal: Boolean; virtual;
procedure WaitStrict; virtual;
Function Wait: Boolean; virtual;
Function TimedWait(Timeout: UInt32): TLSOWaitResult; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
TSimpleEventBase
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSimpleEventBase - class declaration
===============================================================================}
type
TSimpleEventBase = class(TImplementorLinSyncObject)
protected
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
class Function WakeCount: Integer; virtual; abstract;
public
procedure LockStrict; virtual;
Function Lock: Boolean; virtual;
procedure UnlockStrict; virtual;
Function Unlock: Boolean; virtual;
procedure WaitStrict; virtual; abstract;
Function Wait: Boolean; virtual; abstract;
Function TryWaitStrict: Boolean; virtual; abstract;
Function TryWait: Boolean; virtual; abstract;
Function TimedWait(Timeout: UInt32): TLSOWaitResult; virtual; abstract;
end;
{===============================================================================
--------------------------------------------------------------------------------
TSimpleManualEvent
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSimpleManualEvent - flat interface declaration
===============================================================================}
Function event_manual_init(event: PLSOSimpleEvent): cInt;
Function event_manual_destroy(event: PLSOSimpleEvent): cInt;
Function event_manual_lock(event: PLSOSimpleEvent): cInt;
Function event_manual_unlock(event: PLSOSimpleEvent): cInt;
Function event_manual_wait(event: PLSOSimpleEvent): cInt;
Function event_manual_trywait(event: PLSOSimpleEvent): cInt;
Function event_manual_timedwait(event: PLSOSimpleEvent; timeout: cUnsigned): cInt;
{===============================================================================
TSimpleManualEvent - class declaration
===============================================================================}
type
TSimpleManualEvent = class(TSimpleEventBase)
protected
class Function GetLockType: TLSOLockType; override;
class Function WakeCount: Integer; override;
public
procedure WaitStrict; override;
Function Wait: Boolean; override;
Function TryWaitStrict: Boolean; override;
Function TryWait: Boolean; override;
Function TimedWait(Timeout: UInt32): TLSOWaitResult; override;
end;
TSimpleEvent = TSimpleManualEvent;
{===============================================================================
--------------------------------------------------------------------------------
TSimpleAutoEvent
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSimpleAutoEvent - flat interface declaration
===============================================================================}
Function event_auto_init(event: PLSOSimpleEvent): cInt;
Function event_auto_destroy(event: PLSOSimpleEvent): cInt;
Function event_auto_lock(event: PLSOSimpleEvent): cInt;
Function event_auto_unlock(event: PLSOSimpleEvent): cInt;
Function event_auto_wait(event: PLSOSimpleEvent): cInt;
Function event_auto_trywait(event: PLSOSimpleEvent): cInt;
Function event_auto_timedwait(event: PLSOSimpleEvent; timeout: cUnsigned): cInt;
{===============================================================================
TSimpleAutoEvent - class declaration
===============================================================================}
type
TSimpleAutoEvent = class(TSimpleEventBase)
protected
class Function GetLockType: TLSOLockType; override;
class Function WakeCount: Integer; override;
public
procedure WaitStrict; override;
Function Wait: Boolean; override;
Function TryWaitStrict: Boolean; override;
Function TryWait: Boolean; override;
Function TimedWait(Timeout: UInt32): TLSOWaitResult; override;
end;
{===============================================================================
--------------------------------------------------------------------------------
TEvent
--------------------------------------------------------------------------------
===============================================================================}
type
TLSOMultiWaitSlotIndex = Int16;
TLSOWaiterItem = packed record
SlotIndex: TLSOMultiWaitSlotIndex;
WaitAll: Boolean;
end;
TLSOEvent = record
DataLock: TFutexWord;
WaitFutex: TFutexWord;
Signaled: Boolean;
ManualReset: Boolean;
WaiterCount: Integer;
Waiters: packed array[0..15] of TLSOWaiterItem;
end;
PLSOEvent = ^TLSOEvent;
{===============================================================================
TEvent - flat interface declaration
===============================================================================}
Function event_init(event: PLSOEvent; manual_reset, initial_state: cBool): cInt;
Function event_destroy(event: PLSOEvent): cInt;
Function event_lock(event: PLSOEvent): cInt;
Function event_unlock(event: PLSOEvent): cInt;
Function event_wait(event: PLSOEvent): cInt;
Function event_trywait(event: PLSOEvent): cInt;
Function event_timedwait(event: PLSOEvent; timeout: cUnsigned): cInt;
{===============================================================================
TEvent - class declaration
===============================================================================}
type
TEvent = class(TImplementorLinSyncObject)
protected
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
constructor Create(const Name: String; ManualReset,InitialState: Boolean); overload; virtual;
constructor Create(ManualReset,InitialState: Boolean); overload; virtual;
constructor Create(const Name: String); override; // ManualReset := True, InitialState := False
constructor Create; override;
procedure LockStrict; virtual;
Function Lock: Boolean; virtual;
procedure UnlockStrict; virtual;
Function Unlock: Boolean; virtual;
procedure WaitStrict; virtual;
Function Wait: Boolean; virtual;
Function TryWaitStrict: Boolean; virtual;
Function TryWait: Boolean; virtual;
Function TimedWait(Timeout: UInt32): TLSOWaitResult; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
TWrapperLinSynObject
--------------------------------------------------------------------------------
===============================================================================}
{
TWrapperLinSyncObject serves as a base class for objects that are directly
wrapping a pthread-provided synchronization primitive.
}
{===============================================================================
TWrapperLinSynObject - class declaration
===============================================================================}
type
TWrapperLinSyncObject = class(TLinSyncObject);
{===============================================================================
--------------------------------------------------------------------------------
TSpinLock
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSpinLock - class declaration
===============================================================================}
type
TSpinLock = class(TWrapperLinSyncObject)
protected
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
procedure LockStrict; virtual;
Function Lock: Boolean; virtual;
Function TryLockStrict: Boolean; virtual;
Function TryLock: Boolean; virtual;
procedure UnlockStrict; virtual;
Function Unlock: Boolean; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
TMutex
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TMutex - class declaration
===============================================================================}
type
TMutex = class(TWrapperLinSyncObject)
protected
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
procedure LockStrict; virtual;
Function Lock: Boolean; virtual;
Function TryLockStrict: Boolean; virtual;
Function TryLock: Boolean; virtual;
Function TimedLock(Timeout: UInt32): TLSOWaitResult; virtual;
procedure UnlockStrict; virtual;
Function Unlock: Boolean; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
TSemaphore
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TSemaphore - class declaration
===============================================================================}
type
TSemaphore = class(TWrapperLinSyncObject)
protected
fInitialValue: cUnsigned;
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
constructor Create(const Name: String; InitialValue: cUnsigned); overload; virtual;
constructor Create(InitialValue: cUnsigned); overload; virtual;
constructor Create(const Name: String); override;
constructor Create; override;
Function GetValueStrict: cInt; virtual;
Function GetValue: cInt; virtual;
procedure WaitStrict; virtual;
Function Wait: Boolean; virtual;
Function TryWaitStrict: Boolean; virtual;
Function TryWait: Boolean; virtual;
Function TimedWait(Timeout: UInt32): TLSOWaitResult; virtual;
procedure PostStrict; virtual;
Function Post: Boolean; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
TReadWriteLock
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TReadWriteLock - class declaration
===============================================================================}
type
TReadWriteLock = class(TWrapperLinSyncObject)
protected
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
procedure ReadLockStrict; virtual;
Function ReadLock: Boolean; virtual;
Function TryReadLockStrict: Boolean; virtual;
Function TryReadLock: Boolean; virtual;
Function TimedReadLock(Timeout: UInt32): TLSOWaitResult; virtual;
procedure WriteLockStrict; virtual;
Function WriteLock: Boolean virtual;
Function TryWriteLockStrict: Boolean; virtual;
Function TryWriteLock: Boolean; virtual;
Function TimedWriteLock(Timeout: UInt32): TLSOWaitResult; virtual;
procedure UnlockStrict; virtual; // there is no read- or write-specific unlock
Function Unlock: Boolean; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
TConditionVariable
--------------------------------------------------------------------------------
===============================================================================}
type
// types for autocycle
TLSOWakeOption = (woWakeOne,woWakeAll,woWakeBeforeUnlock);
TLSOWakeOptions = set of TLSOWakeOption;
TLSOPredicateCheckEvent = procedure(Sender: TObject; var Predicate: Boolean) of object;
TLSOPredicateCheckCallback = procedure(Sender: TObject; var Predicate: Boolean);
TLSODataAccessEvent = procedure(Sender: TObject; var WakeOptions: TLSOWakeOptions) of object;
TLSODataAccessCallback = procedure(Sender: TObject; var WakeOptions: TLSOWakeOptions);
{===============================================================================
TConditionVariable - class declaration
===============================================================================}
type
TConditionVariable = class(TWrapperLinSyncObject)
protected
// autocycle events
fOnPredicateCheckEvent: TLSOPredicateCheckEvent;
fOnPredicateCheckCallback: TLSOPredicateCheckCallback;
fOnDataAccessEvent: TLSODataAccessEvent;
fOnDataAccessCallback: TLSODataAccessCallback;
// autocycle methods
Function DoOnPredicateCheck: Boolean; virtual;
Function DoOnDataAccess: TLSOWakeOptions; virtual;
procedure SelectWake(WakeOptions: TLSOWakeOptions); virtual;
// inherited methods
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
procedure WaitStrict(DataLock: ppthread_mutex_t); overload; virtual;
procedure WaitStrict(DataLock: TMutex); overload; virtual;
Function Wait(DataLock: ppthread_mutex_t): Boolean; overload; virtual;
Function Wait(DataLock: TMutex): Boolean; overload; virtual;
Function TimedWait(DataLock: ppthread_mutex_t; Timeout: UInt32): TLSOWaitResult; overload; virtual;
Function TimedWait(DataLock: TMutex; Timeout: UInt32): TLSOWaitResult; overload; virtual;
procedure SignalStrict; virtual;
Function Signal: Boolean; virtual;
procedure BroadcastStrict; virtual;
Function Broadcast: Boolean; virtual;
procedure AutoCycle(DataLock: ppthread_mutex_t; Timeout: UInt32); overload; virtual;
procedure AutoCycle(DataLock: TMutex; Timeout: UInt32); overload; virtual;
procedure AutoCycle(DataLock: ppthread_mutex_t); overload; virtual;
procedure AutoCycle(DataLock: TMutex); overload; virtual;
// events
property OnPredicateCheckEvent: TLSOPredicateCheckEvent read fOnPredicateCheckEvent write fOnPredicateCheckEvent;
property OnPredicateCheckCallback: TLSOPredicateCheckCallback read fOnPredicateCheckCallback write fOnPredicateCheckCallback;
property OnPredicateCheck: TLSOPredicateCheckEvent read fOnPredicateCheckEvent write fOnPredicateCheckEvent;
property OnDataAccessEvent: TLSODataAccessEvent read fOnDataAccessEvent write fOnDataAccessEvent;
property OnDataAccessCallback: TLSODataAccessCallback read fOnDataAccessCallback write fOnDataAccessCallback;
property OnDataAccess: TLSODataAccessEvent read fOnDataAccessEvent write fOnDataAccessEvent;
end;
{===============================================================================
--------------------------------------------------------------------------------
TConditionVariableEx
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TConditionVariableEx - class declaration
===============================================================================}
type
TConditionVariableEx = class(TConditionVariable)
protected
fDataLockPtr: Pointer;
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
procedure LockStrict; virtual;
Function Lock: Boolean; virtual;
procedure UnlockStrict; virtual;
Function Unlock: Boolean; virtual;
procedure WaitStrict; overload; virtual;
Function Wait: Boolean; overload; virtual;
Function TimedWait(Timeout: UInt32): TLSOWaitResult; overload; virtual;
procedure AutoCycle(Timeout: UInt32); overload; virtual;
procedure AutoCycle; overload; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
TBarrier
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TBarrier - class declaration
===============================================================================}
type
TBarrier = class(TWrapperLinSyncObject)
protected
class Function GetLockType: TLSOLockType; override;
procedure ResolveLockPtr; override;
procedure InitializeLock(InitializingData: PtrUInt; var CompleteStage: Integer); override;
procedure FinalizeLock(CompleteStage: Integer = MAXINT); override;
public
constructor Create(const Name: String; Count: cUnsigned); overload; virtual;
constructor Create(Count: cUnsigned); overload; virtual;
constructor Create(const Name: String); override;
constructor Create; override;
procedure WaitStrict; virtual;
Function Wait: Boolean; virtual;
end;
{===============================================================================
--------------------------------------------------------------------------------
Wait functions
--------------------------------------------------------------------------------
===============================================================================}
{
Given the implementation, there are limitations in effect for multi-wait
functions, those are:
- there is a system-wide limit of 15360 concurently running instances of
multi-wait (ie. limit of multi-waits active at any one moment)
- single event object can be waited upon in at most 16 multi-waits at one
time
- the number of events in parameter Objects is not strictly limited, but it
is not recommended to go above 32 (there is a technical limit of about 4
bilion objects)
When WaitAll is set to false and the function returns wrSignaled, then the
output parameter Index will contain zero-based index of object that caused
the function to return.
When wrError is returned, then the index is set to one of the following error
codes to indicate what caused the function to fail.
In all other cases, the value of Index is undefined.
}
const
LSO_WAITERROR_UNKNOWN = 1; // some unknown or unspecified error
LSO_WAITERROR_COUNT = 2; // zero object count
LSO_WAITERROR_OBJECTS = 3; // invalid object(s) (unassigned, duplicate, ...)
LSO_WAITERROR_NOSLOT = 4; // reached limit of concurently running instances of multi-wait
LSO_WAITERROR_EVENTFULL = 5; // at least one event has full waiter array and cannot be waited upon
LSO_WAITERROR_FUTEXWAIT = 6; // error in internla waiting mechanism
//------------------------------------------------------------------------------
Function WaitForMultipleEvents(Objects: array of PLSOEvent; WaitAll: Boolean; Timeout: DWORD; out Index: Integer): TLSOWaitResult;
Function WaitForMultipleEvents(Objects: array of PLSOEvent; WaitAll: Boolean; Timeout: DWORD): TLSOWaitResult;
Function WaitForMultipleEvents(Objects: array of PLSOEvent; WaitAll: Boolean): TLSOWaitResult;
Function WaitForMultipleEvents(Objects: array of TEvent; WaitAll: Boolean; Timeout: DWORD; out Index: Integer): TLSOWaitResult;
Function WaitForMultipleEvents(Objects: array of TEvent; WaitAll: Boolean; Timeout: DWORD): TLSOWaitResult;
Function WaitForMultipleEvents(Objects: array of TEvent; WaitAll: Boolean): TLSOWaitResult;
{===============================================================================
--------------------------------------------------------------------------------
Utility functions
--------------------------------------------------------------------------------
===============================================================================}
{
WaitResultToStr returns textual representation of a given wait result.
Meant mainly for debugging.
}
Function WaitResultToStr(WaitResult: TLSOWaitResult): String;
implementation
uses
Math, UnixType, Linux, Errors,
InterlockedOps, BitOps;
{$IFDEF FPC_DisableWarns}
{$DEFINE FPCDWM}
{$DEFINE W5024:={$WARN 5024 OFF}} // Parameter "$1" not used
{$ENDIF}
{===============================================================================
Error checking and management
===============================================================================}
threadvar
ThrErrorCode: cInt;
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Function CheckResErr(ReturnedValue: cInt): Boolean;
begin
Result := ReturnedValue = 0;
If Result then
ThrErrorCode := 0
else
ThrErrorCode := ReturnedValue;
end;
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Function CheckErr(ReturnedValue: cInt): Boolean;
begin
Result := ReturnedValue = 0;
If Result then
ThrErrorCode := 0
else
ThrErrorCode := errno;
end;
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Function errno_ptr: pcInt; cdecl; external name '__errno_location';
Function CheckErrAlt(ReturnedValue: cInt): Boolean;
begin
Result := ReturnedValue = 0;
If Result then
ThrErrorCode := 0
else
ThrErrorCode := errno_ptr^;
end;
{===============================================================================
--------------------------------------------------------------------------------
TCriticalSection
--------------------------------------------------------------------------------
===============================================================================}
Function pthread_mutex_consistent(mutex: ppthread_mutex_t): cInt; cdecl; external;
Function pthread_mutexattr_getrobust(attr: ppthread_mutexattr_t; robustness: pcInt): cInt; cdecl; external;
Function pthread_mutexattr_setrobust(attr: ppthread_mutexattr_t; robustness: cInt): cInt; cdecl; external;
const
//PTHREAD_MUTEX_STALLED = 0; // not used anywhere
PTHREAD_MUTEX_ROBUST = 1;
{===============================================================================
TCriticalSection - class implementation
===============================================================================}
{-------------------------------------------------------------------------------
TCriticalSection - protected methods
-------------------------------------------------------------------------------}
procedure TCriticalSection.Initialize;
var
MutexAttr: pthread_mutexattr_t;
begin
fLockComplete := False;
If CheckResErr(pthread_mutexattr_init(@MutexAttr)) then
try
If not CheckResErr(pthread_mutexattr_settype(@MutexAttr,PTHREAD_MUTEX_RECURSIVE)) then
raise ELSOSysOpError.CreateFmt('TCriticalSection.Initialize: ' +
'Failed to set mutex attribute TYPE (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
If not CheckResErr(pthread_mutexattr_setrobust(@MutexAttr,PTHREAD_MUTEX_ROBUST)) then
raise ELSOSysOpError.CreateFmt('TCriticalSection.Initialize: ' +
'Failed to set mutex attribute ROBUST (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
If not CheckResErr(pthread_mutex_init(@fMutex,@MutexAttr)) then
raise ELSOSysInitError.CreateFmt('TCriticalSection.Initialize: ' +
'Failed to initialize mutex (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
fLockComplete := True;
finally
If not CheckResErr(pthread_mutexattr_destroy(@MutexAttr)) then
raise ELSOSysFinalError.CreateFmt('TCriticalSection.Initialize: ' +
'Failed to destroy mutex attributes (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
end
else raise ELSOSysInitError.CreateFmt('TCriticalSection.Initialize: ' +
'Failed to initialize mutex attributes (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
end;
//------------------------------------------------------------------------------
procedure TCriticalSection.Finalize;
begin
If fLockComplete then
If not CheckResErr(pthread_mutex_destroy(@fMutex)) then
raise ELSOSysFinalError.CreateFmt('TCriticalSection.Finalize: ' +
'Failed to destroy mutex (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
end;
{-------------------------------------------------------------------------------
TCriticalSection - public methods
-------------------------------------------------------------------------------}
constructor TCriticalSection.Create;
begin
inherited Create;
Initialize;
end;
//------------------------------------------------------------------------------
destructor TCriticalSection.Destroy;
begin
Finalize;
inherited;
end;
//------------------------------------------------------------------------------
Function TCriticalSection.TryEnter: Boolean;
var
ReturnValue: cInt;
begin
ReturnValue := pthread_mutex_trylock(@fMutex);
If ReturnValue = ESysEOWNERDEAD then
begin
If not CheckResErr(pthread_mutex_consistent(@fMutex)) then
raise ELSOSysOpError.CreateFmt('TCriticalSection.TryEnter: ' +
'Failed to make mutex consistent (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
Result := True;
end
else
begin
Result := CheckResErr(ReturnValue);
If not Result and (ThrErrorCode <> ESysEBUSY) then
raise ELSOSysOpError.CreateFmt('TCriticalSection.TryEnter: ' +
'Failed to try-lock mutex (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
end;
end;
//------------------------------------------------------------------------------
procedure TCriticalSection.Enter;
var
ReturnValue: cInt;
begin
ReturnValue := pthread_mutex_lock(@fMutex);
If ReturnValue = ESysEOWNERDEAD then
begin
If not CheckResErr(pthread_mutex_consistent(@fMutex)) then
raise ELSOSysOpError.CreateFmt('TCriticalSection.Enter: ' +
'Failed to make mutex consistent (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
end
else
begin
If not CheckResErr(ReturnValue) then
raise ELSOSysOpError.CreateFmt('TCriticalSection.Enter: ' +
'Failed to lock mutex (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
end;
end;
//------------------------------------------------------------------------------
procedure TCriticalSection.Leave;
begin
If not CheckResErr(pthread_mutex_unlock(@fMutex)) then
raise ELSOSysOpError.CreateFmt('TCriticalSection.Leave: ' +
'Failed to unlock mutex (%d - %s).',[ThrErrorCode,StrError(ThrErrorCode)]);
end;
{===============================================================================
--------------------------------------------------------------------------------
TLinSyncObject
--------------------------------------------------------------------------------
===============================================================================}
{===============================================================================
TLinSyncObject - internals
===============================================================================}
const
MSECS_PER_SEC = 1000;
NSECS_PER_SEC = 1000000000;
NSECS_PER_MSEC = 1000000;