]> git.lizzy.rs Git - rust.git/commitdiff
Added example to `compiler_fence` docs taken from unstable-book
authorMichal Budzynski <budziq@gmail.com>
Fri, 15 Sep 2017 15:03:09 +0000 (17:03 +0200)
committerMichal Budzynski <budziq@gmail.com>
Sat, 16 Sep 2017 20:18:46 +0000 (22:18 +0200)
src/libcore/sync/atomic.rs

index c6291630a35f3c2a6ff2da330152d2b7317f85f4..8e4625b71592753c3d9aed0b96093eac27c5f7dd 100644 (file)
@@ -1695,6 +1695,40 @@ pub fn fence(order: Ordering) {
 ///
 /// Panics if `order` is [`Relaxed`].
 ///
+/// # Examples
+///
+/// Without `compiler_fence`, the `assert_eq!` in following code
+/// is *not* guaranteed to succeed, despite everything happening in a single thread.
+/// To see why, remember that the compiler is free to swap the stores to
+/// `IMPORTANT_VARIABLE` and `IS_READ` since they are both
+/// `Ordering::Relaxed`. If it does, and the signal handler is invoked right
+/// after `IS_READY` is updated, then the signal handler will see
+/// `IS_READY=1`, but `IMPORTANT_VARIABLE=0`.
+/// Using a `compiler_fence` remedies this situation.
+///
+/// ```
+/// use std::sync::atomic::{AtomicBool, AtomicUsize};
+/// use std::sync::atomic::{ATOMIC_BOOL_INIT, ATOMIC_USIZE_INIT};
+/// use std::sync::atomic::Ordering;
+/// use std::sync::atomic::compiler_fence;
+///
+/// static IMPORTANT_VARIABLE: AtomicUsize = ATOMIC_USIZE_INIT;
+/// static IS_READY: AtomicBool = ATOMIC_BOOL_INIT;
+///
+/// fn main() {
+///     IMPORTANT_VARIABLE.store(42, Ordering::Relaxed);
+///     // prevent earlier writes from being moved beyond this point
+///     compiler_fence(Ordering::Release);
+///     IS_READY.store(true, Ordering::Relaxed);
+/// }
+///
+/// fn signal_handler() {
+///     if IS_READY.load(Ordering::Relaxed) {
+///         assert_eq!(IMPORTANT_VARIABLE.load(Ordering::Relaxed), 42);
+///     }
+/// }
+/// ```
+///
 /// [`fence`]: fn.fence.html
 /// [`Ordering`]: enum.Ordering.html
 /// [`Acquire`]: enum.Ordering.html#variant.Acquire