Skip to content

Commit 291b6e8

Browse files
authored
Unrolled build for rust-lang#119138
Rollup merge of rust-lang#119138 - AngelicosPhosphoros:use_proper_atomics_in_spinlock_example, r=Nilstrieb Docs: Use non-SeqCst in module example of atomics I done this for this reasons: 1. The example now shows that there is more Orderings than just SeqCst. 2. People who would copy from example would now have more suitable orderings for the job. 3. SeqCst is both much harder to reason about and not needed in most situations. IMHO, we should encourage people to think and use memory orderings that is suitable to task instead of blindly defaulting to SeqCst. r? `@m-ou-se`
2 parents 92d7277 + 1c5b2ce commit 291b6e8

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

library/core/src/sync/atomic.rs

+9-4
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@
138138
//!
139139
//! In general, *all* atomic accesses on read-only memory are Undefined Behavior. For instance, attempting
140140
//! to do a `compare_exchange` that will definitely fail (making it conceptually a read-only
141-
//! operation) can still cause a page fault if the underlying memory page is mapped read-only. Since
141+
//! operation) can still cause a segmentation fault if the underlying memory page is mapped read-only. Since
142142
//! atomic `load`s might be implemented using compare-exchange operations, even a `load` can fault
143143
//! on read-only memory.
144144
//!
@@ -181,12 +181,13 @@
181181
//! let spinlock = Arc::new(AtomicUsize::new(1));
182182
//!
183183
//! let spinlock_clone = Arc::clone(&spinlock);
184+
//!
184185
//! let thread = thread::spawn(move|| {
185-
//! spinlock_clone.store(0, Ordering::SeqCst);
186+
//! spinlock_clone.store(0, Ordering::Release);
186187
//! });
187188
//!
188189
//! // Wait for the other thread to release the lock
189-
//! while spinlock.load(Ordering::SeqCst) != 0 {
190+
//! while spinlock.load(Ordering::Acquire) != 0 {
190191
//! hint::spin_loop();
191192
//! }
192193
//!
@@ -203,7 +204,11 @@
203204
//!
204205
//! static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);
205206
//!
206-
//! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::SeqCst);
207+
//! // Note that Relaxed ordering doesn't synchronize anything
208+
//! // except the global thread counter itself.
209+
//! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::Relaxed);
210+
//! // Note that this number may not be true at the moment of printing
211+
//! // because some other thread may have changed static value already.
207212
//! println!("live threads: {}", old_thread_count + 1);
208213
//! ```
209214

0 commit comments

Comments
 (0)