about summary refs log tree commit diff
diff options
context:
space:
mode:
authorMikail Bagishov <bagishov.mikail@yandex.ru>2023-01-08 22:53:51 +0300
committerGitHub <noreply@github.com>2023-01-08 22:53:51 +0300
commit7b9f64475ed51fbf8221ecb8c7f4fc9e71fa1d53 (patch)
treea0e24b38968398b29659f56801e047b04f8757b2
parentfa51fc01ca3d654d08d627b1d1482d1b77e5ed8b (diff)
downloadrust-7b9f64475ed51fbf8221ecb8c7f4fc9e71fa1d53.tar.gz
rust-7b9f64475ed51fbf8221ecb8c7f4fc9e71fa1d53.zip
Change memory ordering in System wrapper example
Currently, the `SeqCst` ordering is used, which seems unnecessary:
+ Even `Relaxed` ordering guarantees that all updates are atomic and are executed in total order
+ User code only reads atomic for monitoring purposes, no "happens-before" relationships with actual allocations and deallocations are needed for this

If argumentation above is correct, I propose changing ordering to `Relaxed` to clarify that no synchronization is required here, and improve performance (if somebody copy-pastes this example into their code).
-rw-r--r--library/std/src/alloc.rs8
1 files changed, 4 insertions, 4 deletions
diff --git a/library/std/src/alloc.rs b/library/std/src/alloc.rs
index c5a5991cc81..ec774e62deb 100644
--- a/library/std/src/alloc.rs
+++ b/library/std/src/alloc.rs
@@ -93,7 +93,7 @@ pub use alloc_crate::alloc::*;
 ///
 /// ```rust
 /// use std::alloc::{System, GlobalAlloc, Layout};
-/// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
+/// use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
 ///
 /// struct Counter;
 ///
@@ -103,14 +103,14 @@ pub use alloc_crate::alloc::*;
 ///     unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
 ///         let ret = System.alloc(layout);
 ///         if !ret.is_null() {
-///             ALLOCATED.fetch_add(layout.size(), SeqCst);
+///             ALLOCATED.fetch_add(layout.size(), Relaxed);
 ///         }
 ///         ret
 ///     }
 ///
 ///     unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
 ///         System.dealloc(ptr, layout);
-///         ALLOCATED.fetch_sub(layout.size(), SeqCst);
+///         ALLOCATED.fetch_sub(layout.size(), Relaxed);
 ///     }
 /// }
 ///
@@ -118,7 +118,7 @@ pub use alloc_crate::alloc::*;
 /// static A: Counter = Counter;
 ///
 /// fn main() {
-///     println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
+///     println!("allocated bytes before main: {}", ALLOCATED.load(Relaxed));
 /// }
 /// ```
 ///