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).
This commit is contained in:
Mikail Bagishov 2023-01-08 22:53:51 +03:00 committed by GitHub
parent fa51fc01ca
commit 7b9f64475e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -93,7 +93,7 @@
///
/// ```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 @@
/// 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 @@
/// static A: Counter = Counter;
///
/// fn main() {
/// println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
/// println!("allocated bytes before main: {}", ALLOCATED.load(Relaxed));
/// }
/// ```
///