Skip to content

Commit ccc68fb

Browse files
authored
Rollup merge of rust-lang#106599 - MikailBag:patch-1, r=jyn514
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).
2 parents 254e614 + 7b9f644 commit ccc68fb

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

library/std/src/alloc.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ pub use alloc_crate::alloc::*;
9393
///
9494
/// ```rust
9595
/// use std::alloc::{System, GlobalAlloc, Layout};
96-
/// use std::sync::atomic::{AtomicUsize, Ordering::SeqCst};
96+
/// use std::sync::atomic::{AtomicUsize, Ordering::Relaxed};
9797
///
9898
/// struct Counter;
9999
///
@@ -103,22 +103,22 @@ pub use alloc_crate::alloc::*;
103103
/// unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
104104
/// let ret = System.alloc(layout);
105105
/// if !ret.is_null() {
106-
/// ALLOCATED.fetch_add(layout.size(), SeqCst);
106+
/// ALLOCATED.fetch_add(layout.size(), Relaxed);
107107
/// }
108108
/// ret
109109
/// }
110110
///
111111
/// unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
112112
/// System.dealloc(ptr, layout);
113-
/// ALLOCATED.fetch_sub(layout.size(), SeqCst);
113+
/// ALLOCATED.fetch_sub(layout.size(), Relaxed);
114114
/// }
115115
/// }
116116
///
117117
/// #[global_allocator]
118118
/// static A: Counter = Counter;
119119
///
120120
/// fn main() {
121-
/// println!("allocated bytes before main: {}", ALLOCATED.load(SeqCst));
121+
/// println!("allocated bytes before main: {}", ALLOCATED.load(Relaxed));
122122
/// }
123123
/// ```
124124
///

0 commit comments

Comments
 (0)