Skip to content

Commit

Permalink
Rollup merge of #106599 - MikailBag:patch-1, r=jyn514
Browse files Browse the repository at this point in the history
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).
  • Loading branch information
matthiaskrgr authored Apr 27, 2023
2 parents aa22867 + 7b9f644 commit 2148942
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions library/std/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
///
Expand All @@ -103,22 +103,22 @@ 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);
/// }
/// }
///
/// #[global_allocator]
/// static A: Counter = Counter;
///
/// fn main() {
/// println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
/// println!("allocated bytes before main: {}", ALLOCATED.load(Relaxed));
/// }
/// ```
///
Expand Down

0 comments on commit 2148942

Please sign in to comment.