This repository was archived by the owner on Oct 12, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 419
/
Copy pathatomic.d
1403 lines (1237 loc) · 45 KB
/
atomic.d
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
/**
* The atomic module provides basic support for lock-free
* concurrent programming.
*
* Copyright: Copyright Sean Kelly 2005 - 2016.
* License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Authors: Sean Kelly, Alex Rønne Petersen, Manu Evans
* Source: $(DRUNTIMESRC core/_atomic.d)
*/
module core.atomic;
import core.internal.atomic;
import core.internal.attributes : betterC;
import core.internal.traits : hasUnsharedIndirections;
/**
* Specifies the memory ordering semantics of an atomic operation.
*
* See_Also:
* $(HTTP en.cppreference.com/w/cpp/atomic/memory_order)
*/
enum MemoryOrder
{
/**
* Not sequenced.
* Corresponds to $(LINK2 https://llvm.org/docs/Atomics.html#monotonic, LLVM AtomicOrdering.Monotonic)
* and C++11/C11 `memory_order_relaxed`.
*/
raw = 0,
/**
* Hoist-load + hoist-store barrier.
* Corresponds to $(LINK2 https://llvm.org/docs/Atomics.html#acquire, LLVM AtomicOrdering.Acquire)
* and C++11/C11 `memory_order_acquire`.
*/
acq = 2,
/**
* Sink-load + sink-store barrier.
* Corresponds to $(LINK2 https://llvm.org/docs/Atomics.html#release, LLVM AtomicOrdering.Release)
* and C++11/C11 `memory_order_release`.
*/
rel = 3,
/**
* Acquire + release barrier.
* Corresponds to $(LINK2 https://llvm.org/docs/Atomics.html#acquirerelease, LLVM AtomicOrdering.AcquireRelease)
* and C++11/C11 `memory_order_acq_rel`.
*/
acq_rel = 4,
/**
* Fully sequenced (acquire + release). Corresponds to
* $(LINK2 https://llvm.org/docs/Atomics.html#sequentiallyconsistent, LLVM AtomicOrdering.SequentiallyConsistent)
* and C++11/C11 `memory_order_seq_cst`.
*/
seq = 5,
}
/**
* Loads 'val' from memory and returns it. The memory barrier specified
* by 'ms' is applied to the operation, which is fully sequenced by
* default. Valid memory orders are MemoryOrder.raw, MemoryOrder.acq,
* and MemoryOrder.seq.
*
* Params:
* val = The target variable.
*
* Returns:
* The value of 'val'.
*/
T atomicLoad(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope const T val) pure nothrow @nogc @trusted
if (!is(T == shared U, U) && !is(T == shared inout U, U) && !is(T == shared const U, U))
{
static if (__traits(isFloating, T))
{
alias IntTy = IntForFloat!T;
IntTy r = core.internal.atomic.atomicLoad!ms(cast(IntTy*)&val);
return *cast(T*)&r;
}
else
return core.internal.atomic.atomicLoad!ms(cast(T*)&val);
}
/// Ditto
T atomicLoad(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope shared const T val) pure nothrow @nogc @trusted
if (!hasUnsharedIndirections!T)
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!T, "Copying `" ~ shared(const(T)).stringof ~ "` would violate shared.");
return atomicLoad!ms(*cast(T*)&val);
}
/// Ditto
TailShared!T atomicLoad(MemoryOrder ms = MemoryOrder.seq, T)(ref shared const T val) pure nothrow @nogc @trusted
if (hasUnsharedIndirections!T)
{
// HACK: DEPRECATE THIS FUNCTION, IT IS INVALID TO DO ATOMIC LOAD OF SHARED CLASS
// this is here because code exists in the wild that does this...
return core.internal.atomic.atomicLoad!ms(cast(TailShared!T*)&val);
}
/**
* Writes 'newval' into 'val'. The memory barrier specified by 'ms' is
* applied to the operation, which is fully sequenced by default.
* Valid memory orders are MemoryOrder.raw, MemoryOrder.rel, and
* MemoryOrder.seq.
*
* Params:
* val = The target variable.
* newval = The value to store.
*/
void atomicStore(MemoryOrder ms = MemoryOrder.seq, T, V)(ref T val, V newval) pure nothrow @nogc @trusted
if (!is(T == shared) && !is(V == shared))
{
import core.internal.traits : hasElaborateCopyConstructor;
static assert (!hasElaborateCopyConstructor!T, "`T` may not have an elaborate copy: atomic operations override regular copying semantics.");
// resolve implicit conversions
T arg = newval;
static if (__traits(isFloating, T))
{
alias IntTy = IntForFloat!T;
core.internal.atomic.atomicStore!ms(cast(IntTy*)&val, *cast(IntTy*)&arg);
}
else
core.internal.atomic.atomicStore!ms(&val, arg);
}
/// Ditto
void atomicStore(MemoryOrder ms = MemoryOrder.seq, T, V)(ref shared T val, V newval) pure nothrow @nogc @trusted
if (!is(T == class))
{
static if (is (V == shared U, U))
alias Thunk = U;
else
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!V, "Copying argument `" ~ V.stringof ~ " newval` to `" ~ shared(T).stringof ~ " here` would violate shared.");
alias Thunk = V;
}
atomicStore!ms(*cast(T*)&val, *cast(Thunk*)&newval);
}
/// Ditto
void atomicStore(MemoryOrder ms = MemoryOrder.seq, T, V)(ref shared T val, shared V newval) pure nothrow @nogc @trusted
if (is(T == class))
{
static assert (is (V : T), "Can't assign `newval` of type `shared " ~ V.stringof ~ "` to `shared " ~ T.stringof ~ "`.");
core.internal.atomic.atomicStore!ms(cast(T*)&val, cast(V)newval);
}
/**
* Atomically adds `mod` to the value referenced by `val` and returns the value `val` held previously.
* This operation is both lock-free and atomic.
*
* Params:
* val = Reference to the value to modify.
* mod = The value to add.
*
* Returns:
* The value held previously by `val`.
*/
T atomicFetchAdd(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope T val, size_t mod) pure nothrow @nogc @trusted
if ((__traits(isIntegral, T) || is(T == U*, U)) && !is(T == shared))
in (atomicValueIsProperlyAligned(val))
{
static if (is(T == U*, U))
return cast(T)core.internal.atomic.atomicFetchAdd!ms(cast(size_t*)&val, mod * U.sizeof);
else
return core.internal.atomic.atomicFetchAdd!ms(&val, cast(T)mod);
}
/// Ditto
T atomicFetchAdd(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope shared T val, size_t mod) pure nothrow @nogc @trusted
if (__traits(isIntegral, T) || is(T == U*, U))
in (atomicValueIsProperlyAligned(val))
{
return atomicFetchAdd!ms(*cast(T*)&val, mod);
}
/**
* Atomically subtracts `mod` from the value referenced by `val` and returns the value `val` held previously.
* This operation is both lock-free and atomic.
*
* Params:
* val = Reference to the value to modify.
* mod = The value to subtract.
*
* Returns:
* The value held previously by `val`.
*/
T atomicFetchSub(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope T val, size_t mod) pure nothrow @nogc @trusted
if ((__traits(isIntegral, T) || is(T == U*, U)) && !is(T == shared))
in (atomicValueIsProperlyAligned(val))
{
static if (is(T == U*, U))
return cast(T)core.internal.atomic.atomicFetchSub!ms(cast(size_t*)&val, mod * U.sizeof);
else
return core.internal.atomic.atomicFetchSub!ms(&val, cast(T)mod);
}
/// Ditto
T atomicFetchSub(MemoryOrder ms = MemoryOrder.seq, T)(ref return scope shared T val, size_t mod) pure nothrow @nogc @trusted
if (__traits(isIntegral, T) || is(T == U*, U))
in (atomicValueIsProperlyAligned(val))
{
return atomicFetchSub!ms(*cast(T*)&val, mod);
}
/**
* Exchange `exchangeWith` with the memory referenced by `here`.
* This operation is both lock-free and atomic.
*
* Params:
* here = The address of the destination variable.
* exchangeWith = The value to exchange.
*
* Returns:
* The value held previously by `here`.
*/
T atomicExchange(MemoryOrder ms = MemoryOrder.seq,T,V)(T* here, V exchangeWith) pure nothrow @nogc @trusted
if (!is(T == shared) && !is(V == shared))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
// resolve implicit conversions
T arg = exchangeWith;
static if (__traits(isFloating, T))
{
alias IntTy = IntForFloat!T;
IntTy r = core.internal.atomic.atomicExchange!ms(cast(IntTy*)here, *cast(IntTy*)&arg);
return *cast(shared(T)*)&r;
}
else
return core.internal.atomic.atomicExchange!ms(here, arg);
}
/// Ditto
TailShared!T atomicExchange(MemoryOrder ms = MemoryOrder.seq,T,V)(shared(T)* here, V exchangeWith) pure nothrow @nogc @trusted
if (!is(T == class) && !is(T == interface))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
static if (is (V == shared U, U))
alias Thunk = U;
else
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!V, "Copying `exchangeWith` of type `" ~ V.stringof ~ "` to `" ~ shared(T).stringof ~ "` would violate shared.");
alias Thunk = V;
}
return atomicExchange!ms(cast(T*)here, *cast(Thunk*)&exchangeWith);
}
/// Ditto
shared(T) atomicExchange(MemoryOrder ms = MemoryOrder.seq,T,V)(shared(T)* here, shared(V) exchangeWith) pure nothrow @nogc @trusted
if (is(T == class) || is(T == interface))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
static assert (is (V : T), "Can't assign `exchangeWith` of type `" ~ shared(V).stringof ~ "` to `" ~ shared(T).stringof ~ "`.");
return cast(shared)core.internal.atomic.atomicExchange!ms(cast(T*)here, cast(V)exchangeWith);
}
/**
* Converts a shared lvalue to a non-shared lvalue.
*
* This functions allows to treat a shared lvalue as if it was thread-local.
* It is useful to avoid overhead of atomic operations when access to shared data
* is known to be within one thread (i.e. always under a lock).
* ---
* shared static int i;
*
* // i is never used outside of synchronized {} blocks...
*
* synchronized
* {
* ++i; // ERROR: cannot directly modify shared lvalue
*
* atomicOp!"+="(i, 1); // possible overhead
*
* // Directly modify i
* assumeUnshared(i) += 1;
* // or:
* ++assumeUnshared(i);
* // or:
* i.assumeUnshared += 1;
* }
* ---
* Usage of this function is restricted to allowing limited lvalue access to shared instances of
* primitive and POD types (e.g. direct use of operators), thus it is not defined for classes.
*
* Note: this function does not perform any ordering.
*
* Note: `assumeUnshared` is a special-purpose primitive and should be used with care. When accessing
* shared variables both inside and outside of synchronized blocks, atomic operations should be
* used instead.
*
* Note: the result of assumeUnshared is an object for which `shared` has been stripped transitively.
* Therefore, any field that is accessed from the assumed unshared object will also be unshared.
*
* Params:
* val = the shared lvalue.
*
* Returns:
* The non-shared lvalue.
*/
ref T assumeUnshared(T)(ref shared T val) @system @nogc pure nothrow
if (!is(T == class) && !is(T == interface))
{
return *cast(T*) &val;
}
/**
* Performs either compare-and-set or compare-and-swap (or exchange).
*
* There are two categories of overloads in this template:
* The first category does a simple compare-and-set.
* The comparison value (`ifThis`) is treated as an rvalue.
*
* The second category does a compare-and-swap (a.k.a. compare-and-exchange),
* and expects `ifThis` to be a pointer type, where the previous value
* of `here` will be written.
*
* This operation is both lock-free and atomic.
*
* Params:
* here = The address of the destination variable.
* writeThis = The value to store.
* ifThis = The comparison value.
*
* Returns:
* true if the store occurred, false if not.
*/
template cas(MemoryOrder succ = MemoryOrder.seq, MemoryOrder fail = MemoryOrder.seq)
{
/// Compare-and-set for non-shared values
bool cas(T, V1, V2)(T* here, V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
if (!is(T == shared) && is(T : V1))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
// resolve implicit conversions
T arg1 = ifThis;
T arg2 = writeThis;
static if (__traits(isFloating, T))
{
alias IntTy = IntForFloat!T;
return atomicCompareExchangeStrongNoResult!(succ, fail)(
cast(IntTy*)here, *cast(IntTy*)&arg1, *cast(IntTy*)&arg2);
}
else
return atomicCompareExchangeStrongNoResult!(succ, fail)(here, arg1, arg2);
}
/// Compare-and-set for shared value type
bool cas(T, V1, V2)(shared(T)* here, V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
if (!is(T == class) && (is(T : V1) || is(shared T : V1)))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
static if (is (V1 == shared U1, U1))
alias Thunk1 = U1;
else
alias Thunk1 = V1;
static if (is (V2 == shared U2, U2))
alias Thunk2 = U2;
else
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!V2,
"Copying `" ~ V2.stringof ~ "* writeThis` to `" ~
shared(T).stringof ~ "* here` would violate shared.");
alias Thunk2 = V2;
}
return cas(cast(T*)here, *cast(Thunk1*)&ifThis, *cast(Thunk2*)&writeThis);
}
/// Compare-and-set for `shared` reference type (`class`)
bool cas(T, V1, V2)(shared(T)* here, shared(V1) ifThis, shared(V2) writeThis)
pure nothrow @nogc @trusted
if (is(T == class))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
return atomicCompareExchangeStrongNoResult!(succ, fail)(
cast(T*)here, cast(V1)ifThis, cast(V2)writeThis);
}
/// Compare-and-exchange for non-`shared` types
bool cas(T, V)(T* here, T* ifThis, V writeThis) pure nothrow @nogc @trusted
if (!is(T == shared) && !is(V == shared))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
// resolve implicit conversions
T arg1 = writeThis;
static if (__traits(isFloating, T))
{
alias IntTy = IntForFloat!T;
return atomicCompareExchangeStrong!(succ, fail)(
cast(IntTy*)here, cast(IntTy*)ifThis, *cast(IntTy*)&writeThis);
}
else
return atomicCompareExchangeStrong!(succ, fail)(here, ifThis, writeThis);
}
/// Compare and exchange for mixed-`shared`ness types
bool cas(T, V1, V2)(shared(T)* here, V1* ifThis, V2 writeThis) pure nothrow @nogc @trusted
if (!is(T == class) && (is(T : V1) || is(shared T : V1)))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
static if (is (V1 == shared U1, U1))
alias Thunk1 = U1;
else
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!V1,
"Copying `" ~ shared(T).stringof ~ "* here` to `" ~
V1.stringof ~ "* ifThis` would violate shared.");
alias Thunk1 = V1;
}
static if (is (V2 == shared U2, U2))
alias Thunk2 = U2;
else
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!V2,
"Copying `" ~ V2.stringof ~ "* writeThis` to `" ~
shared(T).stringof ~ "* here` would violate shared.");
alias Thunk2 = V2;
}
static assert (is(T : Thunk1),
"Mismatching types for `here` and `ifThis`: `" ~
shared(T).stringof ~ "` and `" ~ V1.stringof ~ "`.");
return cas(cast(T*)here, cast(Thunk1*)ifThis, *cast(Thunk2*)&writeThis);
}
/// Compare-and-exchange for `class`
bool cas(T, V)(shared(T)* here, shared(T)* ifThis, shared(V) writeThis)
pure nothrow @nogc @trusted
if (is(T == class))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
return atomicCompareExchangeStrong!(succ, fail)(
cast(T*)here, cast(T*)ifThis, cast(V)writeThis);
}
}
/**
* Stores 'writeThis' to the memory referenced by 'here' if the value
* referenced by 'here' is equal to 'ifThis'.
* The 'weak' version of cas may spuriously fail. It is recommended to
* use `casWeak` only when `cas` would be used in a loop.
* This operation is both
* lock-free and atomic.
*
* Params:
* here = The address of the destination variable.
* writeThis = The value to store.
* ifThis = The comparison value.
*
* Returns:
* true if the store occurred, false if not.
*/
bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V1,V2)(T* here, V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
if (!is(T == shared) && is(T : V1))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
// resolve implicit conversions
T arg1 = ifThis;
T arg2 = writeThis;
static if (__traits(isFloating, T))
{
alias IntTy = IntForFloat!T;
return atomicCompareExchangeWeakNoResult!(succ, fail)(cast(IntTy*)here, *cast(IntTy*)&arg1, *cast(IntTy*)&arg2);
}
else
return atomicCompareExchangeWeakNoResult!(succ, fail)(here, arg1, arg2);
}
/// Ditto
bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V1,V2)(shared(T)* here, V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
if (!is(T == class) && (is(T : V1) || is(shared T : V1)))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
static if (is (V1 == shared U1, U1))
alias Thunk1 = U1;
else
alias Thunk1 = V1;
static if (is (V2 == shared U2, U2))
alias Thunk2 = U2;
else
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!V2, "Copying `" ~ V2.stringof ~ "* writeThis` to `" ~ shared(T).stringof ~ "* here` would violate shared.");
alias Thunk2 = V2;
}
return casWeak!(succ, fail)(cast(T*)here, *cast(Thunk1*)&ifThis, *cast(Thunk2*)&writeThis);
}
/// Ditto
bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V1,V2)(shared(T)* here, shared(V1) ifThis, shared(V2) writeThis) pure nothrow @nogc @trusted
if (is(T == class))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
return atomicCompareExchangeWeakNoResult!(succ, fail)(cast(T*)here, cast(V1)ifThis, cast(V2)writeThis);
}
/**
* Stores 'writeThis' to the memory referenced by 'here' if the value
* referenced by 'here' is equal to the value referenced by 'ifThis'.
* The prior value referenced by 'here' is written to `ifThis` and
* returned to the user.
* The 'weak' version of cas may spuriously fail. It is recommended to
* use `casWeak` only when `cas` would be used in a loop.
* This operation is both lock-free and atomic.
*
* Params:
* here = The address of the destination variable.
* writeThis = The value to store.
* ifThis = The address of the value to compare, and receives the prior value of `here` as output.
*
* Returns:
* true if the store occurred, false if not.
*/
bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V)(T* here, T* ifThis, V writeThis) pure nothrow @nogc @trusted
if (!is(T == shared S, S) && !is(V == shared U, U))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
// resolve implicit conversions
T arg1 = writeThis;
static if (__traits(isFloating, T))
{
alias IntTy = IntForFloat!T;
return atomicCompareExchangeWeak!(succ, fail)(cast(IntTy*)here, cast(IntTy*)ifThis, *cast(IntTy*)&writeThis);
}
else
return atomicCompareExchangeWeak!(succ, fail)(here, ifThis, writeThis);
}
/// Ditto
bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V1,V2)(shared(T)* here, V1* ifThis, V2 writeThis) pure nothrow @nogc @trusted
if (!is(T == class) && (is(T : V1) || is(shared T : V1)))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
static if (is (V1 == shared U1, U1))
alias Thunk1 = U1;
else
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!V1, "Copying `" ~ shared(T).stringof ~ "* here` to `" ~ V1.stringof ~ "* ifThis` would violate shared.");
alias Thunk1 = V1;
}
static if (is (V2 == shared U2, U2))
alias Thunk2 = U2;
else
{
import core.internal.traits : hasUnsharedIndirections;
static assert(!hasUnsharedIndirections!V2, "Copying `" ~ V2.stringof ~ "* writeThis` to `" ~ shared(T).stringof ~ "* here` would violate shared.");
alias Thunk2 = V2;
}
static assert (is(T : Thunk1), "Mismatching types for `here` and `ifThis`: `" ~ shared(T).stringof ~ "` and `" ~ V1.stringof ~ "`.");
return casWeak!(succ, fail)(cast(T*)here, cast(Thunk1*)ifThis, *cast(Thunk2*)&writeThis);
}
/// Ditto
bool casWeak(MemoryOrder succ = MemoryOrder.seq,MemoryOrder fail = MemoryOrder.seq,T,V)(shared(T)* here, shared(T)* ifThis, shared(V) writeThis) pure nothrow @nogc @trusted
if (is(T == class))
in (atomicPtrIsProperlyAligned(here), "Argument `here` is not properly aligned")
{
return atomicCompareExchangeWeak!(succ, fail)(cast(T*)here, cast(T*)ifThis, cast(V)writeThis);
}
/**
* Inserts a full load/store memory fence (on platforms that need it). This ensures
* that all loads and stores before a call to this function are executed before any
* loads and stores after the call.
*/
void atomicFence(MemoryOrder order = MemoryOrder.seq)() pure nothrow @nogc @safe
{
core.internal.atomic.atomicFence!order();
}
/**
* Gives a hint to the processor that the calling thread is in a 'spin-wait' loop,
* allowing to more efficiently allocate resources.
*/
void pause() pure nothrow @nogc @safe
{
core.internal.atomic.pause();
}
/**
* Performs the binary operation 'op' on val using 'mod' as the modifier.
*
* Params:
* val = The target variable.
* mod = The modifier to apply.
*
* Returns:
* The result of the operation.
*/
TailShared!T atomicOp(string op, T, V1)(ref shared T val, V1 mod) pure nothrow @nogc @safe
if (__traits(compiles, mixin("*cast(T*)&val" ~ op ~ "mod")))
in (atomicValueIsProperlyAligned(val))
{
// binary operators
//
// + - * / % ^^ &
// | ^ << >> >>> ~ in
// == != < <= > >=
static if (op == "+" || op == "-" || op == "*" || op == "/" ||
op == "%" || op == "^^" || op == "&" || op == "|" ||
op == "^" || op == "<<" || op == ">>" || op == ">>>" ||
op == "~" || // skip "in"
op == "==" || op == "!=" || op == "<" || op == "<=" ||
op == ">" || op == ">=")
{
T get = atomicLoad!(MemoryOrder.raw, T)(val);
mixin("return get " ~ op ~ " mod;");
}
else
// assignment operators
//
// += -= *= /= %= ^^= &=
// |= ^= <<= >>= >>>= ~=
static if (op == "+=" && __traits(isIntegral, T) && __traits(isIntegral, V1) && T.sizeof <= size_t.sizeof && V1.sizeof <= size_t.sizeof)
{
return cast(T)(atomicFetchAdd(val, mod) + mod);
}
else static if (op == "-=" && __traits(isIntegral, T) && __traits(isIntegral, V1) && T.sizeof <= size_t.sizeof && V1.sizeof <= size_t.sizeof)
{
return cast(T)(atomicFetchSub(val, mod) - mod);
}
else static if (op == "+=" || op == "-=" || op == "*=" || op == "/=" ||
op == "%=" || op == "^^=" || op == "&=" || op == "|=" ||
op == "^=" || op == "<<=" || op == ">>=" || op == ">>>=") // skip "~="
{
T set, get = atomicLoad!(MemoryOrder.raw, T)(val);
do
{
set = get;
mixin("set " ~ op ~ " mod;");
} while (!casWeakByRef(val, get, set));
return set;
}
else
{
static assert(false, "Operation not supported.");
}
}
version (D_InlineAsm_X86)
{
enum has64BitXCHG = false;
enum has64BitCAS = true;
enum has128BitCAS = false;
}
else version (D_InlineAsm_X86_64)
{
enum has64BitXCHG = true;
enum has64BitCAS = true;
enum has128BitCAS = true;
}
else version (GNU)
{
import gcc.config;
enum has64BitCAS = GNU_Have_64Bit_Atomics;
enum has64BitXCHG = GNU_Have_64Bit_Atomics;
enum has128BitCAS = GNU_Have_LibAtomic;
}
else
{
enum has64BitXCHG = false;
enum has64BitCAS = false;
enum has128BitCAS = false;
}
private
{
bool atomicValueIsProperlyAligned(T)(ref T val) pure nothrow @nogc @trusted
{
return atomicPtrIsProperlyAligned(&val);
}
bool atomicPtrIsProperlyAligned(T)(T* ptr) pure nothrow @nogc @safe
{
// NOTE: Strictly speaking, the x86 supports atomic operations on
// unaligned values. However, this is far slower than the
// common case, so such behavior should be prohibited.
static if (T.sizeof > size_t.sizeof)
{
version (X86)
{
// cmpxchg8b only requires 4-bytes alignment
return cast(size_t)ptr % size_t.sizeof == 0;
}
else
{
// e.g., x86_64 cmpxchg16b requires 16-bytes alignment
return cast(size_t)ptr % T.sizeof == 0;
}
}
else
{
return cast(size_t)ptr % T.sizeof == 0;
}
}
template IntForFloat(F)
if (__traits(isFloating, F))
{
static if (F.sizeof == 4)
alias IntForFloat = uint;
else static if (F.sizeof == 8)
alias IntForFloat = ulong;
else
static assert (false, "Invalid floating point type: " ~ F.stringof ~ ", only support `float` and `double`.");
}
template IntForStruct(S)
if (is(S == struct))
{
static if (S.sizeof == 1)
alias IntForFloat = ubyte;
else static if (F.sizeof == 2)
alias IntForFloat = ushort;
else static if (F.sizeof == 4)
alias IntForFloat = uint;
else static if (F.sizeof == 8)
alias IntForFloat = ulong;
else static if (F.sizeof == 16)
alias IntForFloat = ulong[2]; // TODO: what's the best type here? slice/delegates pass in registers...
else
static assert (ValidateStruct!S);
}
template ValidateStruct(S)
if (is(S == struct))
{
import core.internal.traits : hasElaborateAssign;
// `(x & (x-1)) == 0` checks that x is a power of 2.
static assert (S.sizeof <= size_t.sizeof * 2
&& (S.sizeof & (S.sizeof - 1)) == 0,
S.stringof ~ " has invalid size for atomic operations.");
static assert (!hasElaborateAssign!S, S.stringof ~ " may not have an elaborate assignment when used with atomic operations.");
enum ValidateStruct = true;
}
// TODO: it'd be nice if we had @trusted scopes; we could remove this...
bool casWeakByRef(T,V1,V2)(ref T value, ref V1 ifThis, V2 writeThis) pure nothrow @nogc @trusted
{
return casWeak(&value, &ifThis, writeThis);
}
/* Construct a type with a shared tail, and if possible with an unshared
head. */
template TailShared(U) if (!is(U == shared))
{
alias TailShared = .TailShared!(shared U);
}
template TailShared(S) if (is(S == shared))
{
// Get the unshared variant of S.
static if (is(S U == shared U)) {}
else static assert(false, "Should never be triggered. The `static " ~
"if` declares `U` as the unshared version of the shared type " ~
"`S`. `S` is explicitly declared as shared, so getting `U` " ~
"should always work.");
static if (is(S : U))
alias TailShared = U;
else static if (is(S == struct))
{
enum implName = () {
/* Start with "_impl". If S has a field with that name, append
underscores until the clash is resolved. */
string name = "_impl";
string[] fieldNames;
static foreach (alias field; S.tupleof)
{
fieldNames ~= __traits(identifier, field);
}
static bool canFind(string[] haystack, string needle)
{
foreach (candidate; haystack)
{
if (candidate == needle) return true;
}
return false;
}
while (canFind(fieldNames, name)) name ~= "_";
return name;
} ();
struct TailShared
{
static foreach (i, alias field; S.tupleof)
{
/* On @trusted: This is casting the field from shared(Foo)
to TailShared!Foo. The cast is safe because the field has
been loaded and is not shared anymore. */
mixin("
@trusted @property
ref " ~ __traits(identifier, field) ~ "()
{
alias R = TailShared!(typeof(field));
return * cast(R*) &" ~ implName ~ ".tupleof[i];
}
");
}
mixin("
S " ~ implName ~ ";
alias " ~ implName ~ " this;
");
}
}
else
alias TailShared = S;
}
@safe unittest
{
// No tail (no indirections) -> fully unshared.
static assert(is(TailShared!int == int));
static assert(is(TailShared!(shared int) == int));
static struct NoIndir { int i; }
static assert(is(TailShared!NoIndir == NoIndir));
static assert(is(TailShared!(shared NoIndir) == NoIndir));
// Tail can be independently shared or is already -> tail-shared.
static assert(is(TailShared!(int*) == shared(int)*));
static assert(is(TailShared!(shared int*) == shared(int)*));
static assert(is(TailShared!(shared(int)*) == shared(int)*));
static assert(is(TailShared!(int[]) == shared(int)[]));
static assert(is(TailShared!(shared int[]) == shared(int)[]));
static assert(is(TailShared!(shared(int)[]) == shared(int)[]));
static struct S1 { shared int* p; }
static assert(is(TailShared!S1 == S1));
static assert(is(TailShared!(shared S1) == S1));
static struct S2 { shared(int)* p; }
static assert(is(TailShared!S2 == S2));
static assert(is(TailShared!(shared S2) == S2));
// Tail follows shared-ness of head -> fully shared.
static class C { int i; }
static assert(is(TailShared!C == shared C));
static assert(is(TailShared!(shared C) == shared C));
/* However, structs get a wrapper that has getters which cast to
TailShared. */
static struct S3 { int* p; int _impl; int _impl_; int _impl__; }
static assert(!is(TailShared!S3 : S3));
static assert(is(TailShared!S3 : shared S3));
static assert(is(TailShared!(shared S3) == TailShared!S3));
static struct S4 { shared(int)** p; }
static assert(!is(TailShared!S4 : S4));
static assert(is(TailShared!S4 : shared S4));
static assert(is(TailShared!(shared S4) == TailShared!S4));
}
}
////////////////////////////////////////////////////////////////////////////////
// Unit Tests
////////////////////////////////////////////////////////////////////////////////
version (CoreUnittest)
{
version (D_LP64)
{
enum hasDWCAS = has128BitCAS;
}
else
{
enum hasDWCAS = has64BitCAS;
}
void testXCHG(T)(T val) pure nothrow @nogc @trusted
in
{
assert(val !is T.init);
}
do
{
T base = cast(T)null;
shared(T) atom = cast(shared(T))null;
assert(base !is val, T.stringof);
assert(atom is base, T.stringof);
assert(atomicExchange(&atom, val) is base, T.stringof);
assert(atom is val, T.stringof);
}
void testCAS(T)(T val) pure nothrow @nogc @trusted
in
{
assert(val !is T.init);
}
do
{
T base = cast(T)null;
shared(T) atom = cast(shared(T))null;
assert(base !is val, T.stringof);
assert(atom is base, T.stringof);
assert(cas(&atom, base, val), T.stringof);
assert(atom is val, T.stringof);
assert(!cas(&atom, base, base), T.stringof);
assert(atom is val, T.stringof);
atom = cast(shared(T))null;
shared(T) arg = base;
assert(cas(&atom, &arg, val), T.stringof);
assert(arg is base, T.stringof);
assert(atom is val, T.stringof);
arg = base;
assert(!cas(&atom, &arg, base), T.stringof);
assert(arg is val, T.stringof);
assert(atom is val, T.stringof);
}
void testLoadStore(MemoryOrder ms = MemoryOrder.seq, T)(T val = T.init + 1) pure nothrow @nogc @trusted
{
T base = cast(T) 0;
shared(T) atom = cast(T) 0;
assert(base !is val);
assert(atom is base);
atomicStore!(ms)(atom, val);
base = atomicLoad!(ms)(atom);
assert(base is val, T.stringof);
assert(atom is val);
}
void testType(T)(T val = T.init + 1) pure nothrow @nogc @safe
{
static if (T.sizeof < 8 || has64BitXCHG)
testXCHG!(T)(val);
testCAS!(T)(val);
testLoadStore!(MemoryOrder.seq, T)(val);
testLoadStore!(MemoryOrder.raw, T)(val);
}
@betterC @safe pure nothrow unittest
{
testType!(bool)();
testType!(byte)();
testType!(ubyte)();
testType!(short)();
testType!(ushort)();
testType!(int)();
testType!(uint)();
}
@safe pure nothrow unittest
{
testType!(shared int*)();
static interface Inter {}
static class KlassImpl : Inter {}
testXCHG!(shared Inter)(new shared(KlassImpl));
testCAS!(shared Inter)(new shared(KlassImpl));
static class Klass {}
testXCHG!(shared Klass)(new shared(Klass));
testCAS!(shared Klass)(new shared(Klass));
testXCHG!(shared int)(42);
testType!(float)(0.1f);
static if (has64BitCAS)
{
testType!(double)(0.1);
testType!(long)();
testType!(ulong)();