-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathJclSynch.pas
1772 lines (1603 loc) · 53.2 KB
/
JclSynch.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
{**************************************************************************************************}
{ }
{ Project JEDI Code Library (JCL) }
{ }
{ The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); }
{ you may not use this file except in compliance with the License. You may obtain a copy of the }
{ License at http://www.mozilla.org/MPL/ }
{ }
{ Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF }
{ ANY KIND, either express or implied. See the License for the specific language governing rights }
{ and limitations under the License. }
{ }
{ The Original Code is JclSynch.pas. }
{ }
{ The Initial Developers of the Original Code are Marcel van Brakel and Azret Botash. }
{ Portions created by these individuals are Copyright (C) of these individuals. }
{ All Rights Reserved. }
{ }
{ Contributor(s): }
{ Marcel van Brakel }
{ Olivier Sannier (obones) }
{ Matthias Thoma (mthoma) }
{ }
{**************************************************************************************************}
{ }
{ This unit contains various classes and support routines for implementing synchronisation in }
{ multithreaded applications. This ranges from interlocked access to simple typed variables to }
{ wrapper classes for synchronisation primitives provided by the operating system }
{ (critical section, semaphore, mutex etc). It also includes three user defined classes to }
{ complement these. }
{ }
{**************************************************************************************************}
{ }
{ Last modified: $Date:: $ }
{ Revision: $Rev:: $ }
{ Author: $Author:: $ }
{ }
{**************************************************************************************************}
unit JclSynch;
//{$I jcl.inc}
interface
uses
{$IFDEF UNITVERSIONING}
JclUnitVersioning,
{$ENDIF UNITVERSIONING}
{$IFDEF HAS_UNITSCOPE}
{$IFDEF MSWINDOWS}
Winapi.Windows, JclWin32,
{$ENDIF MSWINDOWS}
{$ELSE ~HAS_UNITSCOPE}
{$IFDEF MSWINDOWS}
Windows, JclWin32,
{$ENDIF MSWINDOWS}
{$ENDIF ~HAS_UNITSCOPE}
JclBase;
// Locked Integer manipulation
//
// Routines to manipulate simple typed variables in a thread safe manner
function LockedAdd(var Target: Integer; Value: Integer): Integer; overload;
function LockedCompareExchange(var Target: Integer; Exch, Comp: Integer): Integer; overload;
function LockedCompareExchange(var Target: TObject; Exch, Comp: TObject): TObject; overload;
function LockedCompareExchange(var Target: Pointer; Exch, Comp: Pointer): Pointer; overload;
function LockedDec(var Target: Integer): Integer; overload;
function LockedExchange(var Target: Integer; Value: Integer): Integer; overload;
function LockedExchangeAdd(var Target: Integer; Value: Integer): Integer; overload;
function LockedExchangeDec(var Target: Integer): Integer; overload;
function LockedExchangeInc(var Target: Integer): Integer; overload;
function LockedExchangeSub(var Target: Integer; Value: Integer): Integer; overload;
function LockedInc(var Target: Integer): Integer; overload;
function LockedSub(var Target: Integer; Value: Integer): Integer; overload;
{$IFDEF CPU64}
function LockedAdd(var Target: Int64; Value: Int64): Int64; overload;
function LockedCompareExchange(var Target: Int64; Exch, Comp: Int64): Int64; overload;
function LockedDec(var Target: Int64): Int64; overload;
function LockedExchange(var Target: Int64; Value: Int64): Int64; overload;
function LockedExchangeAdd(var Target: Int64; Value: Int64): Int64; overload;
function LockedExchangeDec(var Target: Int64): Int64; overload;
function LockedExchangeInc(var Target: Int64): Int64; overload;
function LockedExchangeSub(var Target: Int64; Value: Int64): Int64; overload;
function LockedInc(var Target: Int64): Int64; overload;
function LockedSub(var Target: Int64; Value: Int64): Int64; overload;
{$IFDEF BORLAND}
function LockedDec(var Target: NativeInt): NativeInt; overload;
function LockedInc(var Target: NativeInt): NativeInt; overload;
{$ENDIF BORLAND}
{$ENDIF CPU64}
// TJclDispatcherObject
//
// Base class for operating system provided synchronisation primitives
type
TJclWaitResult = (wrAbandoned, wrError, wrIoCompletion, wrSignaled, wrTimeout);
TJclWaitHandle = THandle;
TJclDispatcherObject = class(TObject)
private
FExisted: Boolean;
FHandle: TJclWaitHandle;
FName: string;
public
constructor Attach(AHandle: TJclWaitHandle);
destructor Destroy; override;
//function MsgWaitFor(const TimeOut: Cardinal): TJclWaitResult; Mask: DWORD): TJclWaitResult;
//function MsgWaitForEx(const TimeOut: Cardinal): TJclWaitResult; Mask: DWORD): TJclWaitResult;
function SignalAndWait(const Obj: TJclDispatcherObject; TimeOut: Cardinal;
Alertable: Boolean): TJclWaitResult;
function WaitAlertable(const TimeOut: Cardinal): TJclWaitResult;
function WaitFor(const TimeOut: Cardinal): TJclWaitResult;
function WaitForever: TJclWaitResult;
property Existed: Boolean read FExisted;
property Handle: TJclWaitHandle read FHandle;
property Name: string read FName;
end;
// Wait functions
//
// Object enabled Wait functions (takes TJclDispatcher objects as parameter as
// opposed to handles) mostly for convenience
function WaitForMultipleObjects(const Objects: array of TJclDispatcherObject;
WaitAll: Boolean; TimeOut: Cardinal): Cardinal;
function WaitAlertableForMultipleObjects(const Objects: array of TJclDispatcherObject;
WaitAll: Boolean; TimeOut: Cardinal): Cardinal;
type
TJclCriticalSection = class(TObject)
private
FCriticalSection: TRTLCriticalSection;
public
constructor Create; virtual;
destructor Destroy; override;
class procedure CreateAndEnter(var CS: TJclCriticalSection);
procedure Enter;
procedure Leave;
end;
TJclCriticalSectionEx = class(TJclCriticalSection)
private
FSpinCount: Cardinal;
function GetSpinCount: Cardinal;
procedure SetSpinCount(const Value: Cardinal);
public
constructor Create; override;
constructor CreateEx(SpinCount: Cardinal; NoFailEnter: Boolean); virtual;
class function GetSpinTimeOut: Cardinal;
class procedure SetSpinTimeOut(const Value: Cardinal);
function TryEnter: Boolean;
property SpinCount: Cardinal read GetSpinCount write SetSpinCount;
end;
TJclEvent = class(TJclDispatcherObject)
public
constructor Create(SecAttr: PSecurityAttributes; Manual, Signaled: Boolean; const Name: string);
constructor Open(Access: Cardinal; Inheritable: Boolean; const Name: string);
function Pulse: Boolean;
function ResetEvent: Boolean;
function SetEvent: Boolean;
end;
TJclWaitableTimer = class(TJclDispatcherObject)
private
FResume: Boolean;
public
constructor Create(SecAttr: PSecurityAttributes; Manual: Boolean; const Name: string);
constructor Open(Access: Cardinal; Inheritable: Boolean; const Name: string);
function Cancel: Boolean;
function SetTimer(const DueTime: Int64; Period: Longint; Resume: Boolean): Boolean;
function SetTimerApc(const DueTime: Int64; Period: Longint; Resume: Boolean; Apc: TFNTimerAPCRoutine; Arg: Pointer): Boolean;
end;
TJclSemaphore = class(TJclDispatcherObject)
public
constructor Create(SecAttr: PSecurityAttributes; Initial, Maximum: Longint; const Name: string);
constructor Open(Access: Cardinal; Inheritable: Boolean; const Name: string);
function Release(ReleaseCount: Longint): Boolean;
function ReleasePrev(ReleaseCount: Longint; var PrevCount: Longint): Boolean;
end;
TJclMutex = class(TJclDispatcherObject)
public
constructor Create(SecAttr: PSecurityAttributes; InitialOwner: Boolean;
const Name: string);
constructor Open(Access: Cardinal; Inheritable: Boolean; const Name: string);
function Acquire(const TimeOut: Cardinal = INFINITE): Boolean;
function Release: Boolean;
end;
POptexSharedInfo = ^TOptexSharedInfo;
TOptexSharedInfo = record
SpinCount: Integer; // number of times to try and enter the optex before
// waiting on kernel event, 0 on single processor
LockCount: Integer; // count of enter attempts
ThreadId: Longword; // id of thread that owns the optex, 0 if free
RecursionCount: Integer; // number of times the optex is owned, 0 if free
end;
TJclOptex = class(TObject)
private
FEvent: TJclEvent;
FExisted: Boolean;
FFileMapping: THandle;
FName: string;
FSharedInfo: POptexSharedInfo;
function GetUniProcess: Boolean;
function GetSpinCount: Integer;
procedure SetSpinCount(Value: Integer);
public
constructor Create(const Name: string = ''; SpinCount: Integer = 4000);
destructor Destroy; override;
procedure Enter;
procedure Leave;
function TryEnter: Boolean;
property Existed: Boolean read FExisted;
property Name: string read FName;
property SpinCount: Integer read GetSpinCount write SetSpinCount;
property UniProcess: Boolean read GetUniProcess;
end;
TMrewPreferred = (mpReaders, mpWriters, mpEqual);
TMrewThreadInfo = record
ThreadId: Longword; // client-id of thread
RecursionCount: Integer; // number of times a thread accessed the mrew
Reader: Boolean; // true if reader, false if writer
end;
TMrewThreadInfoArray = array of TMrewThreadInfo;
TJclMultiReadExclusiveWrite = class(TObject)
private
FLock: TJclCriticalSection;
FPreferred: TMrewPreferred;
FSemReaders: TJclSemaphore;
FSemWriters: TJclSemaphore;
FState: Integer;
FThreads: TMrewThreadInfoArray;
FWaitingReaders: Integer;
FWaitingWriters: Integer;
procedure AddToThreadList(ThreadId: Longword; Reader: Boolean);
procedure RemoveFromThreadList(Index: Integer);
function FindThread(ThreadId: Longword): Integer;
procedure ReleaseWaiters(WasReading: Boolean);
protected
procedure Release;
public
constructor Create(Preferred: TMrewPreferred);
destructor Destroy; override;
procedure BeginRead;
procedure BeginWrite;
procedure EndRead;
procedure EndWrite;
end;
PMetSectSharedInfo = ^TMetSectSharedInfo;
TMetSectSharedInfo = record
Initialized: LongBool; // Is the metered section initialized?
SpinLock: Longint; // Used to gain access to this structure
ThreadsWaiting: Longint; // Count of threads waiting
AvailableCount: Longint; // Available resource count
MaximumCount: Longint; // Maximum resource count
end;
PMeteredSection = ^TMeteredSection;
TMeteredSection = record
Event: THandle; // Handle to a kernel event object
FileMap: THandle; // Handle to memory mapped file
SharedInfo: PMetSectSharedInfo;
end;
TJclMeteredSection = class(TObject)
private
FMetSect: PMeteredSection;
procedure CloseMeteredSection;
function InitMeteredSection(InitialCount, MaxCount: Longint; const Name: string; OpenOnly: Boolean): Boolean;
function CreateMetSectEvent(const Name: string; OpenOnly: Boolean): Boolean;
function CreateMetSectFileView(InitialCount, MaxCount: Longint; const Name: string; OpenOnly: Boolean): Boolean;
protected
procedure AcquireLock;
procedure ReleaseLock;
public
constructor Create(InitialCount, MaxCount: Longint; const Name: string);
constructor Open(const Name: string);
destructor Destroy; override;
function Enter(TimeOut: Longword): TJclWaitResult;
function Leave(ReleaseCount: Longint): Boolean; overload;
function Leave(ReleaseCount: Longint; out PrevCount: Longint): Boolean; overload;
end;
// Debugging
//
// Note that the following function and structure declarations are all offically
// undocumented and, except for QueryCriticalSection, require Windows NT since
// it is all part of the Windows NT Native API.
{ TODO -cTest : Test this structures }
type
TEventInfo = record
EventType: Longint; // 0 = manual, otherwise auto
Signaled: LongBool; // true is signaled
end;
TMutexInfo = record
SignalState: Longint; // >0 = signaled, <0 = |SignalState| recurs. acquired
Owned: ByteBool; // owned by thread
Abandoned: ByteBool; // is abandoned?
end;
TSemaphoreCounts = record
CurrentCount: Longint; // current semaphore count
MaximumCount: Longint; // maximum semaphore count
end;
TTimerInfo = record
Remaining: TLargeInteger; // 100ns intervals until signaled
Signaled: ByteBool; // is signaled?
end;
function QueryCriticalSection(CS: TJclCriticalSection; var Info: TRTLCriticalSection): Boolean;
{ TODO -cTest : Test these 4 functions }
function QueryEvent(Handle: THandle; var Info: TEventInfo): Boolean;
function QueryMutex(Handle: THandle; var Info: TMutexInfo): Boolean;
function QuerySemaphore(Handle: THandle; var Info: TSemaphoreCounts): Boolean;
function QueryTimer(Handle: THandle; var Info: TTimerInfo): Boolean;
type
// Exceptions
EJclWin32HandleObjectError = class(EJclWin32Error);
EJclDispatcherObjectError = class(EJclWin32Error);
EJclCriticalSectionError = class(EJclWin32Error);
EJclEventError = class(EJclWin32Error);
EJclWaitableTimerError = class(EJclWin32Error);
EJclSemaphoreError = class(EJclWin32Error);
EJclMutexError = class(EJclWin32Error);
EJclMeteredSectionError = class(EJclError);
function ValidateMutexName(const aName: string): string;
{$IFDEF UNITVERSIONING}
const
UnitVersioning: TUnitVersionInfo = (
RCSfile: '$URL$';
Revision: '$Revision$';
Date: '$Date$';
LogPath: 'JCL\source\common';
Extra: '';
Data: nil
);
{$ENDIF UNITVERSIONING}
implementation
uses
{$IFDEF HAS_UNITSCOPE}
System.SysUtils,
{$ELSE ~HAS_UNITSCOPE}
SysUtils,
{$ENDIF ~HAS_UNITSCOPE}
JclLogic, JclRegistry, JclResources,
JclSysInfo, JclStrings;
const
RegSessionManager = {HKLM\} 'SYSTEM\CurrentControlSet\Control\Session Manager';
RegCritSecTimeout = {RegSessionManager\} 'CriticalSectionTimeout';
// Locked Integer manipulation
function LockedAdd(var Target: Integer; Value: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// EDX Value
// <-- EAX Result
MOV ECX, EAX
MOV EAX, EDX
LOCK XADD [ECX], EAX
ADD EAX, EDX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// EDX Value
// <-- EAX Result
MOV EAX, EDX
LOCK XADD [RCX], EAX
ADD EAX, EDX
{$ENDIF CPU64}
end;
function LockedCompareExchange(var Target: Integer; Exch, Comp: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// EDX Exch
// ECX Comp
// <-- EAX Result
XCHG EAX, ECX
// EAX Comp
// EDX Exch
// ECX Target
LOCK CMPXCHG [ECX], EDX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// EDX Exch
// R8 Comp
// <-- EAX Result
MOV RAX, R8
// RCX Target
// EDX Exch
// RAX Comp
LOCK CMPXCHG [RCX], EDX
{$ENDIF CPU64}
end;
function LockedCompareExchange(var Target: Pointer; Exch, Comp: Pointer): Pointer;
asm
{$IFDEF CPU32}
// --> EAX Target
// EDX Exch
// ECX Comp
// <-- EAX Result
XCHG EAX, ECX
// EAX Comp
// EDX Exch
// ECX Target
LOCK CMPXCHG [ECX], EDX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// RDX Exch
// R8 Comp
// <-- RAX Result
MOV RAX, R8
// RCX Target
// RDX Exch
// RAX Comp
LOCK CMPXCHG [RCX], RDX
{$ENDIF CPU64}
end;
function LockedCompareExchange(var Target: TObject; Exch, Comp: TObject): TObject;
asm
{$IFDEF CPU32}
// --> EAX Target
// EDX Exch
// ECX Comp
// <-- EAX Result
XCHG EAX, ECX
// EAX Comp
// EDX Exch
// ECX Target
LOCK CMPXCHG [ECX], EDX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// RDX Exch
// R8 Comp
// <-- RAX Result
MOV RAX, R8
// --> RCX Target
// RDX Exch
// RAX Comp
LOCK CMPXCHG [RCX], RDX
{$ENDIF CPU64}
end;
function LockedDec(var Target: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// <-- EAX Result
MOV ECX, EAX
MOV EAX, -1
LOCK XADD [ECX], EAX
DEC EAX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// <-- EAX Result
MOV EAX, -1
LOCK XADD [RCX], EAX
DEC EAX
{$ENDIF CPU64}
end;
function LockedExchange(var Target: Integer; Value: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// EDX Value
// <-- EAX Result
MOV ECX, EAX
MOV EAX, EDX
// ECX Target
// EAX Value
LOCK XCHG [ECX], EAX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// EDX Value
// <-- EAX Result
MOV EAX, EDX
// RCX Target
// EAX Value
LOCK XCHG [RCX], EAX
{$ENDIF CPU64}
end;
function LockedExchangeAdd(var Target: Integer; Value: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// EDX Value
// <-- EAX Result
MOV ECX, EAX
MOV EAX, EDX
// ECX Target
// EAX Value
LOCK XADD [ECX], EAX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// EDX Value
// <-- EAX Result
MOV EAX, EDX
// RCX Target
// EAX Value
LOCK XADD [RCX], EAX
{$ENDIF CPU64}
end;
function LockedExchangeDec(var Target: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// <-- EAX Result
MOV ECX, EAX
MOV EAX, -1
LOCK XADD [ECX], EAX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// <-- EAX Result
MOV EAX, -1
LOCK XADD [RCX], EAX
{$ENDIF CPU64}
end;
function LockedExchangeInc(var Target: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// <-- EAX Result
MOV ECX, EAX
MOV EAX, 1
LOCK XADD [ECX], EAX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// <-- EAX Result
MOV EAX, 1
LOCK XADD [RCX], EAX
{$ENDIF CPU64}
end;
function LockedExchangeSub(var Target: Integer; Value: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// EDX Value
// <-- EAX Result
MOV ECX, EAX
NEG EDX
MOV EAX, EDX
// ECX Target
// EAX -Value
LOCK XADD [ECX], EAX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// EDX Value
// <-- EAX Result
NEG EDX
MOV EAX, EDX
// RCX Target
// EAX -Value
LOCK XADD [RCX], EAX
{$ENDIF CPU64}
end;
function LockedInc(var Target: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// <-- EAX Result
MOV ECX, EAX
MOV EAX, 1
LOCK XADD [ECX], EAX
INC EAX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// <-- EAX Result
MOV EAX, 1
LOCK XADD [RCX], EAX
INC EAX
{$ENDIF CPU64}
end;
function LockedSub(var Target: Integer; Value: Integer): Integer;
asm
{$IFDEF CPU32}
// --> EAX Target
// EDX Value
// <-- EAX Result
MOV ECX, EAX
NEG EDX
MOV EAX, EDX
LOCK XADD [ECX], EAX
ADD EAX, EDX
{$ENDIF CPU32}
{$IFDEF CPU64}
// --> RCX Target
// EDX Value
// <-- EAX Result
NEG EDX
MOV EAX, EDX
LOCK XADD [RCX], EAX
ADD EAX, EDX
{$ENDIF CPU64}
end;
{$IFDEF CPU64}
// Locked Int64 manipulation
function LockedAdd(var Target: Int64; Value: Int64): Int64;
asm
// --> RCX Target
// RDX Value
// <-- RAX Result
MOV RAX, RDX
LOCK XADD [RCX], RAX
ADD RAX, RDX
end;
function LockedCompareExchange(var Target: Int64; Exch, Comp: Int64): Int64;
asm
// --> RCX Target
// RDX Exch
// R8 Comp
// <-- RAX Result
MOV RAX, R8
LOCK CMPXCHG [RCX], RDX
end;
function LockedDec(var Target: Int64): Int64;
asm
// --> RCX Target
// <-- RAX Result
MOV RAX, -1
LOCK XADD [RCX], RAX
DEC RAX
end;
function LockedExchange(var Target: Int64; Value: Int64): Int64;
asm
// --> RCX Target
// RDX Value
// <-- RAX Result
MOV RAX, RDX
LOCK XCHG [RCX], RAX
end;
function LockedExchangeAdd(var Target: Int64; Value: Int64): Int64;
asm
// --> RCX Target
// RDX Value
// <-- RAX Result
MOV RAX, RDX
LOCK XADD [RCX], RAX
end;
function LockedExchangeDec(var Target: Int64): Int64;
asm
// --> RCX Target
// <-- RAX Result
MOV RAX, -1
LOCK XADD [RCX], RAX
end;
function LockedExchangeInc(var Target: Int64): Int64;
asm
// --> RCX Target
// <-- RAX Result
MOV RAX, 1
LOCK XADD [RCX], RAX
end;
function LockedExchangeSub(var Target: Int64; Value: Int64): Int64;
asm
// --> RCX Target
// RDX Value
// <-- RAX Result
NEG RDX
MOV RAX, RDX
LOCK XADD [RCX], RAX
end;
function LockedInc(var Target: Int64): Int64;
asm
// --> RCX Target
// <-- RAX Result
MOV RAX, 1
LOCK XADD [RCX], RAX
INC RAX
end;
function LockedSub(var Target: Int64; Value: Int64): Int64;
asm
// --> RCX Target
// RDX Value
// <-- RAX Result
NEG RDX
MOV RAX, RDX
LOCK XADD [RCX], RAX
ADD RAX, RDX
end;
{$IFDEF BORLAND}
function LockedDec(var Target: NativeInt): NativeInt;
asm
// --> RCX Target
// <-- RAX Result
MOV RAX, -1
LOCK XADD [RCX], RAX
DEC RAX
end;
function LockedInc(var Target: NativeInt): NativeInt;
asm
// --> RCX Target
// <-- RAX Result
MOV RAX, 1
LOCK XADD [RCX], RAX
INC RAX
end;
{$ENDIF BORLAND}
{$ENDIF CPU64}
//=== { TJclDispatcherObject } ===============================================
function MapSignalResult(const Ret: DWORD): TJclWaitResult;
begin
case Ret of
WAIT_ABANDONED:
Result := wrAbandoned;
WAIT_OBJECT_0:
Result := wrSignaled;
WAIT_TIMEOUT:
Result := wrTimeout;
WAIT_IO_COMPLETION:
Result := wrIoCompletion;
WAIT_FAILED:
Result := wrError;
else
Result := wrError;
end;
end;
constructor TJclDispatcherObject.Attach(AHandle: TJclWaitHandle);
begin
inherited Create;
FExisted := True;
FHandle := AHandle;
FName := '';
end;
destructor TJclDispatcherObject.Destroy;
begin
CloseHandle(FHandle);
inherited Destroy;
end;
{ TODO: Use RTDL Version of SignalObjectAndWait }
function TJclDispatcherObject.SignalAndWait(const Obj: TJclDispatcherObject;
TimeOut: Cardinal; Alertable: Boolean): TJclWaitResult;
begin
// Note: Do not make this method virtual! It's only available on NT 4 up...
Result := MapSignalResult(Cardinal({$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.SignalObjectAndWait(Obj.Handle, Handle, TimeOut, Alertable)));
end;
function TJclDispatcherObject.WaitAlertable(const TimeOut: Cardinal): TJclWaitResult;
begin
Result := MapSignalResult({$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.WaitForSingleObjectEx(FHandle, TimeOut, True));
end;
function TJclDispatcherObject.WaitFor(const TimeOut: Cardinal): TJclWaitResult;
begin
Result := MapSignalResult({$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.WaitForSingleObject(FHandle, TimeOut));
end;
function TJclDispatcherObject.WaitForever: TJclWaitResult;
begin
Result := WaitFor(INFINITE);
end;
// Wait functions
function WaitForMultipleObjects(const Objects: array of TJclDispatcherObject;
WaitAll: Boolean; TimeOut: Cardinal): Cardinal;
var
Handles: array of TJclWaitHandle;
I, Count: Integer;
begin
Count := High(Objects) + 1;
SetLength(Handles, Count);
for I := 0 to Count - 1 do
Handles[I] := Objects[I].Handle;
Result := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.WaitForMultipleObjects(Count, @Handles[0], WaitAll, TimeOut);
end;
function WaitAlertableForMultipleObjects(const Objects: array of TJclDispatcherObject;
WaitAll: Boolean; TimeOut: Cardinal): Cardinal;
var
Handles: array of TJclWaitHandle;
I, Count: Integer;
begin
Count := High(Objects) + 1;
SetLength(Handles, Count);
for I := 0 to Count - 1 do
Handles[I] := Objects[I].Handle;
Result := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.WaitForMultipleObjectsEx(Count, @Handles[0], WaitAll, TimeOut, True);
end;
//=== { TJclCriticalSection } ================================================
constructor TJclCriticalSection.Create;
begin
inherited Create;
{$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.InitializeCriticalSection(FCriticalSection);
end;
destructor TJclCriticalSection.Destroy;
begin
{$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.DeleteCriticalSection(FCriticalSection);
inherited Destroy;
end;
class procedure TJclCriticalSection.CreateAndEnter(var CS: TJclCriticalSection);
var
NewCritSect: TJclCriticalSection;
begin
NewCritSect := TJclCriticalSection.Create;
if LockedCompareExchange(Pointer(CS), Pointer(NewCritSect), nil) <> nil then
begin
// LoadInProgress was <> nil -> no exchange took place, free the CS
NewCritSect.Free;
end;
CS.Enter;
end;
procedure TJclCriticalSection.Enter;
begin
{$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.EnterCriticalSection(FCriticalSection);
end;
procedure TJclCriticalSection.Leave;
begin
{$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.LeaveCriticalSection(FCriticalSection);
end;
//== { TJclCriticalSectionEx } ===============================================
const
DefaultCritSectSpinCount = 4000;
constructor TJclCriticalSectionEx.Create;
begin
CreateEx(DefaultCritSectSpinCount, False);
end;
{ TODO: Use RTDL Version of InitializeCriticalSectionAndSpinCount }
constructor TJclCriticalSectionEx.CreateEx(SpinCount: Cardinal;
NoFailEnter: Boolean);
begin
FSpinCount := SpinCount;
if NoFailEnter then
SpinCount := SpinCount or Cardinal($80000000);
if not InitializeCriticalSectionAndSpinCount(FCriticalSection, SpinCount) then
raise EJclCriticalSectionError.CreateRes(@RsSynchInitCriticalSection);
end;
function TJclCriticalSectionEx.GetSpinCount: Cardinal;
begin
// Spinning only makes sense on multiprocessor systems. On a single processor
// system the thread would simply waste cycles while the owning thread is
// suspended and thus cannot release the critical section.
if ProcessorCount = 1 then
Result := 0
else
Result := FSpinCount;
end;
class function TJclCriticalSectionEx.GetSpinTimeOut: Cardinal;
begin
Result := Cardinal(RegReadInteger(HKEY_LOCAL_MACHINE, RegSessionManager,
RegCritSecTimeout));
end;
{ TODO: Use RTLD version of SetCriticalSectionSpinCount }
procedure TJclCriticalSectionEx.SetSpinCount(const Value: Cardinal);
begin
FSpinCount := SetCriticalSectionSpinCount(FCriticalSection, Value);
end;
class procedure TJclCriticalSectionEx.SetSpinTimeOut(const Value: Cardinal);
begin
RegWriteInteger(HKEY_LOCAL_MACHINE, RegSessionManager, RegCritSecTimeout,
Integer(Value));
end;
{ TODO: Use RTLD version of TryEnterCriticalSection }
function TJclCriticalSectionEx.TryEnter: Boolean;
begin
Result := TryEnterCriticalSection(FCriticalSection);
end;
//== { TJclEvent } ===========================================================
constructor TJclEvent.Create(SecAttr: PSecurityAttributes; Manual, Signaled: Boolean; const Name: string);
begin
inherited Create;
FName := Name;
FHandle := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.CreateEvent(SecAttr, Manual, Signaled, PChar(FName));
if FHandle = 0 then
raise EJclEventError.CreateRes(@RsSynchCreateEvent);
FExisted := GetLastError = ERROR_ALREADY_EXISTS;
end;
constructor TJclEvent.Open(Access: Cardinal; Inheritable: Boolean;
const Name: string);
begin
FName := Name;
FExisted := True;
FHandle := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.OpenEvent(Access, Inheritable, PChar(Name));
if FHandle = 0 then
raise EJclEventError.CreateRes(@RsSynchOpenEvent);
end;
function TJclEvent.Pulse: Boolean;
begin
Result := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.PulseEvent(FHandle);
end;
function TJclEvent.ResetEvent: Boolean;
begin
Result := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.ResetEvent(FHandle);
end;
function TJclEvent.SetEvent: Boolean;
begin
Result := {$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}Windows.SetEvent(FHandle);
end;
//=== { TJclWaitableTimer } ==================================================
{ TODO: Use RTLD version of CreateWaitableTimer }
constructor TJclWaitableTimer.Create(SecAttr: PSecurityAttributes;
Manual: Boolean; const Name: string);
begin
FName := Name;
FResume := False;
FHandle := CreateWaitableTimer(SecAttr, Manual, PChar(Name));
if FHandle = 0 then
raise EJclWaitableTimerError.CreateRes(@RsSynchCreateWaitableTimer);
FExisted := GetLastError = ERROR_ALREADY_EXISTS;
end;
{ TODO: Use RTLD version of CancelWaitableTimer }
function TJclWaitableTimer.Cancel: Boolean;
begin
Result := CancelWaitableTimer(FHandle);
end;
{ TODO: Use RTLD version of OpenWaitableTimer }
constructor TJclWaitableTimer.Open(Access: Cardinal; Inheritable: Boolean;
const Name: string);
begin
FExisted := True;