Skip to content

Commit 2598e45

Browse files
committed
Add safe wrapper for atomic_singlethreadfence_*
1 parent ad5dfec commit 2598e45

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/libcore/sync/atomic.rs

+41
Original file line numberDiff line numberDiff line change
@@ -1572,6 +1572,47 @@ pub fn fence(order: Ordering) {
15721572
}
15731573

15741574

1575+
/// A compiler memory barrier.
1576+
///
1577+
/// `compiler_barrier` does not emit any machine code, but prevents the compiler from re-ordering
1578+
/// memory operations across this point. Which reorderings are disallowed is dictated by the given
1579+
/// [`Ordering`]. Note that `compiler_barrier` does *not* introduce inter-thread memory
1580+
/// synchronization; for that, a [`fence`] is needed.
1581+
///
1582+
/// The re-ordering prevented by the different ordering semantics are:
1583+
///
1584+
/// - with [`SeqCst`], no re-ordering of reads and writes across this point is allowed.
1585+
/// - with [`Release`], preceding reads and writes cannot be moved past subsequent writes.
1586+
/// - with [`Acquire`], subsequent reads and writes cannot be moved ahead of preceding reads.
1587+
/// - with [`AcqRel`], both of the above rules are enforced.
1588+
///
1589+
/// # Panics
1590+
///
1591+
/// Panics if `order` is [`Relaxed`].
1592+
///
1593+
/// [`fence`]: fn.fence.html
1594+
/// [`Ordering`]: enum.Ordering.html
1595+
/// [`Acquire`]: enum.Ordering.html#variant.Acquire
1596+
/// [`SeqCst`]: enum.Ordering.html#variant.SeqCst
1597+
/// [`Release`]: enum.Ordering.html#variant.Release
1598+
/// [`AcqRel`]: enum.Ordering.html#variant.AcqRel
1599+
/// [`Relaxed`]: enum.Ordering.html#variant.Relaxed
1600+
#[inline]
1601+
#[unstable(feature = "std_compiler_fences", issue = "41091")]
1602+
pub fn compiler_barrier(order: Ordering) {
1603+
unsafe {
1604+
match order {
1605+
Acquire => intrinsics::atomic_singlethreadfence_acq(),
1606+
Release => intrinsics::atomic_singlethreadfence_rel(),
1607+
AcqRel => intrinsics::atomic_singlethreadfence_acqrel(),
1608+
SeqCst => intrinsics::atomic_singlethreadfence(),
1609+
Relaxed => panic!("there is no such thing as a relaxed barrier"),
1610+
__Nonexhaustive => panic!("invalid memory ordering"),
1611+
}
1612+
}
1613+
}
1614+
1615+
15751616
#[cfg(target_has_atomic = "8")]
15761617
#[stable(feature = "atomic_debug", since = "1.3.0")]
15771618
impl fmt::Debug for AtomicBool {

0 commit comments

Comments
 (0)