core/sync/atomic.rs
1//! Atomic types
2//!
3//! Atomic types provide primitive shared-memory communication between
4//! threads, and are the building blocks of other concurrent
5//! types.
6//!
7//! This module defines atomic versions of a select number of primitive
8//! types, including [`AtomicBool`], [`AtomicIsize`], [`AtomicUsize`],
9//! [`AtomicI8`], [`AtomicU16`], etc.
10//! Atomic types present operations that, when used correctly, synchronize
11//! updates between threads.
12//!
13//! Atomic variables are safe to share between threads (they implement [`Sync`])
14//! but they do not themselves provide the mechanism for sharing and follow the
15//! [threading model](../../../std/thread/index.html#the-threading-model) of Rust.
16//! The most common way to share an atomic variable is to put it into an [`Arc`][arc] (an
17//! atomically-reference-counted shared pointer).
18//!
19//! [arc]: ../../../std/sync/struct.Arc.html
20//!
21//! Atomic types may be stored in static variables, initialized using
22//! the constant initializers like [`AtomicBool::new`]. Atomic statics
23//! are often used for lazy global initialization.
24//!
25//! ## Memory model for atomic accesses
26//!
27//! Rust atomics currently follow the same rules as [C++20 atomics][cpp], specifically the rules
28//! from the [`intro.races`][cpp-intro.races] section, without the "consume" memory ordering. Since
29//! C++ uses an object-based memory model whereas Rust is access-based, a bit of translation work
30//! has to be done to apply the C++ rules to Rust: whenever C++ talks about "the value of an
31//! object", we understand that to mean the resulting bytes obtained when doing a read. When the C++
32//! standard talks about "the value of an atomic object", this refers to the result of doing an
33//! atomic load (via the operations provided in this module). A "modification of an atomic object"
34//! refers to an atomic store.
35//!
36//! The end result is *almost* equivalent to saying that creating a *shared reference* to one of the
37//! Rust atomic types corresponds to creating an `atomic_ref` in C++, with the `atomic_ref` being
38//! destroyed when the lifetime of the shared reference ends. The main difference is that Rust
39//! permits concurrent atomic and non-atomic reads to the same memory as those cause no issue in the
40//! C++ memory model, they are just forbidden in C++ because memory is partitioned into "atomic
41//! objects" and "non-atomic objects" (with `atomic_ref` temporarily converting a non-atomic object
42//! into an atomic object).
43//!
44//! The most important aspect of this model is that *data races* are undefined behavior. A data race
45//! is defined as conflicting non-synchronized accesses where at least one of the accesses is
46//! non-atomic. Here, accesses are *conflicting* if they affect overlapping regions of memory and at
47//! least one of them is a write. (A `compare_exchange` or `compare_exchange_weak` that does not
48//! succeed is not considered a write.) They are *non-synchronized* if neither of them
49//! *happens-before* the other, according to the happens-before order of the memory model.
50//!
51//! The other possible cause of undefined behavior in the memory model are mixed-size accesses: Rust
52//! inherits the C++ limitation that non-synchronized conflicting atomic accesses may not partially
53//! overlap. In other words, every pair of non-synchronized atomic accesses must be either disjoint,
54//! access the exact same memory (including using the same access size), or both be reads.
55//!
56//! Each atomic access takes an [`Ordering`] which defines how the operation interacts with the
57//! happens-before order. These orderings behave the same as the corresponding [C++20 atomic
58//! orderings][cpp_memory_order]. For more information, see the [nomicon].
59//!
60//! [cpp]: https://en.cppreference.com/w/cpp/atomic
61//! [cpp-intro.races]: https://timsong-cpp.github.io/cppwp/n4868/intro.multithread#intro.races
62//! [cpp_memory_order]: https://en.cppreference.com/w/cpp/atomic/memory_order
63//! [nomicon]: ../../../nomicon/atomics.html
64//!
65//! ```rust,no_run undefined_behavior
66//! use std::sync::atomic::{AtomicU16, AtomicU8, Ordering};
67//! use std::mem::transmute;
68//! use std::thread;
69//!
70//! let atomic = AtomicU16::new(0);
71//!
72//! thread::scope(|s| {
73//! // This is UB: conflicting non-synchronized accesses, at least one of which is non-atomic.
74//! s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store
75//! s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write
76//! });
77//!
78//! thread::scope(|s| {
79//! // This is fine: the accesses do not conflict (as none of them performs any modification).
80//! // In C++ this would be disallowed since creating an `atomic_ref` precludes
81//! // further non-atomic accesses, but Rust does not have that limitation.
82//! s.spawn(|| atomic.load(Ordering::Relaxed)); // atomic load
83//! s.spawn(|| unsafe { atomic.as_ptr().read() }); // non-atomic read
84//! });
85//!
86//! thread::scope(|s| {
87//! // This is fine: `join` synchronizes the code in a way such that the atomic
88//! // store happens-before the non-atomic write.
89//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed)); // atomic store
90//! handle.join().expect("thread won't panic"); // synchronize
91//! s.spawn(|| unsafe { atomic.as_ptr().write(2) }); // non-atomic write
92//! });
93//!
94//! thread::scope(|s| {
95//! // This is UB: non-synchronized conflicting differently-sized atomic accesses.
96//! s.spawn(|| atomic.store(1, Ordering::Relaxed));
97//! s.spawn(|| unsafe {
98//! let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic);
99//! differently_sized.store(2, Ordering::Relaxed);
100//! });
101//! });
102//!
103//! thread::scope(|s| {
104//! // This is fine: `join` synchronizes the code in a way such that
105//! // the 1-byte store happens-before the 2-byte store.
106//! let handle = s.spawn(|| atomic.store(1, Ordering::Relaxed));
107//! handle.join().expect("thread won't panic");
108//! s.spawn(|| unsafe {
109//! let differently_sized = transmute::<&AtomicU16, &AtomicU8>(&atomic);
110//! differently_sized.store(2, Ordering::Relaxed);
111//! });
112//! });
113//! ```
114//!
115//! # Portability
116//!
117//! All atomic types in this module are guaranteed to be [lock-free] if they're
118//! available. This means they don't internally acquire a global mutex. Atomic
119//! types and operations are not guaranteed to be wait-free. This means that
120//! operations like `fetch_or` may be implemented with a compare-and-swap loop.
121//!
122//! Atomic operations may be implemented at the instruction layer with
123//! larger-size atomics. For example some platforms use 4-byte atomic
124//! instructions to implement `AtomicI8`. Note that this emulation should not
125//! have an impact on correctness of code, it's just something to be aware of.
126//!
127//! The atomic types in this module might not be available on all platforms. The
128//! atomic types here are all widely available, however, and can generally be
129//! relied upon existing. Some notable exceptions are:
130//!
131//! * PowerPC and MIPS platforms with 32-bit pointers do not have `AtomicU64` or
132//! `AtomicI64` types.
133//! * ARM platforms like `armv5te` that aren't for Linux only provide `load`
134//! and `store` operations, and do not support Compare and Swap (CAS)
135//! operations, such as `swap`, `fetch_add`, etc. Additionally on Linux,
136//! these CAS operations are implemented via [operating system support], which
137//! may come with a performance penalty.
138//! * ARM targets with `thumbv6m` only provide `load` and `store` operations,
139//! and do not support Compare and Swap (CAS) operations, such as `swap`,
140//! `fetch_add`, etc.
141//!
142//! [operating system support]: https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
143//!
144//! Note that future platforms may be added that also do not have support for
145//! some atomic operations. Maximally portable code will want to be careful
146//! about which atomic types are used. `AtomicUsize` and `AtomicIsize` are
147//! generally the most portable, but even then they're not available everywhere.
148//! For reference, the `std` library requires `AtomicBool`s and pointer-sized atomics, although
149//! `core` does not.
150//!
151//! The `#[cfg(target_has_atomic)]` attribute can be used to conditionally
152//! compile based on the target's supported bit widths. It is a key-value
153//! option set for each supported size, with values "8", "16", "32", "64",
154//! "128", and "ptr" for pointer-sized atomics.
155//!
156//! [lock-free]: https://en.wikipedia.org/wiki/Non-blocking_algorithm
157//!
158//! # Atomic accesses to read-only memory
159//!
160//! In general, *all* atomic accesses on read-only memory are undefined behavior. For instance, attempting
161//! to do a `compare_exchange` that will definitely fail (making it conceptually a read-only
162//! operation) can still cause a segmentation fault if the underlying memory page is mapped read-only. Since
163//! atomic `load`s might be implemented using compare-exchange operations, even a `load` can fault
164//! on read-only memory.
165//!
166//! For the purpose of this section, "read-only memory" is defined as memory that is read-only in
167//! the underlying target, i.e., the pages are mapped with a read-only flag and any attempt to write
168//! will cause a page fault. In particular, an `&u128` reference that points to memory that is
169//! read-write mapped is *not* considered to point to "read-only memory". In Rust, almost all memory
170//! is read-write; the only exceptions are memory created by `const` items or `static` items without
171//! interior mutability, and memory that was specifically marked as read-only by the operating
172//! system via platform-specific APIs.
173//!
174//! As an exception from the general rule stated above, "sufficiently small" atomic loads with
175//! `Ordering::Relaxed` are implemented in a way that works on read-only memory, and are hence not
176//! undefined behavior. The exact size limit for what makes a load "sufficiently small" varies
177//! depending on the target:
178//!
179//! | `target_arch` | Size limit |
180//! |---------------|---------|
181//! | `x86`, `arm`, `loongarch32`, `mips`, `mips32r6`, `powerpc`, `riscv32`, `sparc`, `hexagon` | 4 bytes |
182//! | `x86_64`, `aarch64`, `loongarch64`, `mips64`, `mips64r6`, `powerpc64`, `riscv64`, `sparc64`, `s390x` | 8 bytes |
183//!
184//! Atomics loads that are larger than this limit as well as atomic loads with ordering other
185//! than `Relaxed`, as well as *all* atomic loads on targets not listed in the table, might still be
186//! read-only under certain conditions, but that is not a stable guarantee and should not be relied
187//! upon.
188//!
189//! If you need to do an acquire load on read-only memory, you can do a relaxed load followed by an
190//! acquire fence instead.
191//!
192//! # Examples
193//!
194//! A simple spinlock:
195//!
196//! ```ignore-wasm
197//! use std::sync::Arc;
198//! use std::sync::atomic::{AtomicUsize, Ordering};
199//! use std::{hint, thread};
200//!
201//! fn main() {
202//! let spinlock = Arc::new(AtomicUsize::new(1));
203//!
204//! let spinlock_clone = Arc::clone(&spinlock);
205//!
206//! let thread = thread::spawn(move || {
207//! spinlock_clone.store(0, Ordering::Release);
208//! });
209//!
210//! // Wait for the other thread to release the lock
211//! while spinlock.load(Ordering::Acquire) != 0 {
212//! hint::spin_loop();
213//! }
214//!
215//! if let Err(panic) = thread.join() {
216//! println!("Thread had an error: {panic:?}");
217//! }
218//! }
219//! ```
220//!
221//! Keep a global count of live threads:
222//!
223//! ```
224//! use std::sync::atomic::{AtomicUsize, Ordering};
225//!
226//! static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);
227//!
228//! // Note that Relaxed ordering doesn't synchronize anything
229//! // except the global thread counter itself.
230//! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::Relaxed);
231//! // Note that this number may not be true at the moment of printing
232//! // because some other thread may have changed static value already.
233//! println!("live threads: {}", old_thread_count + 1);
234//! ```
235
236#![stable(feature = "rust1", since = "1.0.0")]
237#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(dead_code))]
238#![cfg_attr(not(target_has_atomic_load_store = "8"), allow(unused_imports))]
239#![rustc_diagnostic_item = "atomic_mod"]
240// Clippy complains about the pattern of "safe function calling unsafe function taking pointers".
241// This happens with AtomicPtr intrinsics but is fine, as the pointers clippy is concerned about
242// are just normal values that get loaded/stored, but not dereferenced.
243#![allow(clippy::not_unsafe_ptr_arg_deref)]
244
245use self::Ordering::*;
246use crate::cell::UnsafeCell;
247use crate::hint::spin_loop;
248use crate::intrinsics::AtomicOrdering as AO;
249use crate::{fmt, intrinsics};
250
251trait Sealed {}
252
253/// A marker trait for primitive types which can be modified atomically.
254///
255/// This is an implementation detail for <code>[Atomic]\<T></code> which may disappear or be replaced at any time.
256///
257/// # Safety
258///
259/// Types implementing this trait must be primitives that can be modified atomically.
260///
261/// The associated `Self::AtomicInner` type must have the same size and bit validity as `Self`,
262/// but may have a higher alignment requirement, so the following `transmute`s are sound:
263///
264/// - `&mut Self::AtomicInner` as `&mut Self`
265/// - `Self` as `Self::AtomicInner` or the reverse
266#[unstable(
267 feature = "atomic_internals",
268 reason = "implementation detail which may disappear or be replaced at any time",
269 issue = "none"
270)]
271#[expect(private_bounds)]
272pub unsafe trait AtomicPrimitive: Sized + Copy + Sealed {
273 /// Temporary implementation detail.
274 type AtomicInner: Sized;
275}
276
277macro impl_atomic_primitive(
278 $Atom:ident $(<$T:ident>)? ($Primitive:ty),
279 size($size:literal),
280 align($align:literal) $(,)?
281) {
282 impl $(<$T>)? Sealed for $Primitive {}
283
284 #[unstable(
285 feature = "atomic_internals",
286 reason = "implementation detail which may disappear or be replaced at any time",
287 issue = "none"
288 )]
289 #[cfg(target_has_atomic_load_store = $size)]
290 unsafe impl $(<$T>)? AtomicPrimitive for $Primitive {
291 type AtomicInner = $Atom $(<$T>)?;
292 }
293}
294
295impl_atomic_primitive!(AtomicBool(bool), size("8"), align(1));
296impl_atomic_primitive!(AtomicI8(i8), size("8"), align(1));
297impl_atomic_primitive!(AtomicU8(u8), size("8"), align(1));
298impl_atomic_primitive!(AtomicI16(i16), size("16"), align(2));
299impl_atomic_primitive!(AtomicU16(u16), size("16"), align(2));
300impl_atomic_primitive!(AtomicI32(i32), size("32"), align(4));
301impl_atomic_primitive!(AtomicU32(u32), size("32"), align(4));
302impl_atomic_primitive!(AtomicI64(i64), size("64"), align(8));
303impl_atomic_primitive!(AtomicU64(u64), size("64"), align(8));
304impl_atomic_primitive!(AtomicI128(i128), size("128"), align(16));
305impl_atomic_primitive!(AtomicU128(u128), size("128"), align(16));
306
307#[cfg(target_pointer_width = "16")]
308impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(2));
309#[cfg(target_pointer_width = "32")]
310impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(4));
311#[cfg(target_pointer_width = "64")]
312impl_atomic_primitive!(AtomicIsize(isize), size("ptr"), align(8));
313
314#[cfg(target_pointer_width = "16")]
315impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(2));
316#[cfg(target_pointer_width = "32")]
317impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(4));
318#[cfg(target_pointer_width = "64")]
319impl_atomic_primitive!(AtomicUsize(usize), size("ptr"), align(8));
320
321#[cfg(target_pointer_width = "16")]
322impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(2));
323#[cfg(target_pointer_width = "32")]
324impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(4));
325#[cfg(target_pointer_width = "64")]
326impl_atomic_primitive!(AtomicPtr<T>(*mut T), size("ptr"), align(8));
327
328/// A memory location which can be safely modified from multiple threads.
329///
330/// This has the same size and bit validity as the underlying type `T`. However,
331/// the alignment of this type is always equal to its size, even on targets where
332/// `T` has alignment less than its size.
333///
334/// For more about the differences between atomic types and non-atomic types as
335/// well as information about the portability of this type, please see the
336/// [module-level documentation].
337///
338/// **Note:** This type is only available on platforms that support atomic loads
339/// and stores of `T`.
340///
341/// [module-level documentation]: crate::sync::atomic
342#[unstable(feature = "generic_atomic", issue = "130539")]
343pub type Atomic<T> = <T as AtomicPrimitive>::AtomicInner;
344
345// Some architectures don't have byte-sized atomics, which results in LLVM
346// emulating them using a LL/SC loop. However for AtomicBool we can take
347// advantage of the fact that it only ever contains 0 or 1 and use atomic OR/AND
348// instead, which LLVM can emulate using a larger atomic OR/AND operation.
349//
350// This list should only contain architectures which have word-sized atomic-or/
351// atomic-and instructions but don't natively support byte-sized atomics.
352#[cfg(target_has_atomic = "8")]
353const EMULATE_ATOMIC_BOOL: bool = cfg!(any(
354 target_arch = "riscv32",
355 target_arch = "riscv64",
356 target_arch = "loongarch32",
357 target_arch = "loongarch64"
358));
359
360/// A boolean type which can be safely shared between threads.
361///
362/// This type has the same size, alignment, and bit validity as a [`bool`].
363///
364/// **Note**: This type is only available on platforms that support atomic
365/// loads and stores of `u8`.
366#[cfg(target_has_atomic_load_store = "8")]
367#[stable(feature = "rust1", since = "1.0.0")]
368#[rustc_diagnostic_item = "AtomicBool"]
369#[repr(C, align(1))]
370pub struct AtomicBool {
371 v: UnsafeCell<u8>,
372}
373
374#[cfg(target_has_atomic_load_store = "8")]
375#[stable(feature = "rust1", since = "1.0.0")]
376impl Default for AtomicBool {
377 /// Creates an `AtomicBool` initialized to `false`.
378 #[inline]
379 fn default() -> Self {
380 Self::new(false)
381 }
382}
383
384// Send is implicitly implemented for AtomicBool.
385#[cfg(target_has_atomic_load_store = "8")]
386#[stable(feature = "rust1", since = "1.0.0")]
387unsafe impl Sync for AtomicBool {}
388
389/// A raw pointer type which can be safely shared between threads.
390///
391/// This type has the same size and bit validity as a `*mut T`.
392///
393/// **Note**: This type is only available on platforms that support atomic
394/// loads and stores of pointers. Its size depends on the target pointer's size.
395#[cfg(target_has_atomic_load_store = "ptr")]
396#[stable(feature = "rust1", since = "1.0.0")]
397#[rustc_diagnostic_item = "AtomicPtr"]
398#[cfg_attr(target_pointer_width = "16", repr(C, align(2)))]
399#[cfg_attr(target_pointer_width = "32", repr(C, align(4)))]
400#[cfg_attr(target_pointer_width = "64", repr(C, align(8)))]
401pub struct AtomicPtr<T> {
402 p: UnsafeCell<*mut T>,
403}
404
405#[cfg(target_has_atomic_load_store = "ptr")]
406#[stable(feature = "rust1", since = "1.0.0")]
407impl<T> Default for AtomicPtr<T> {
408 /// Creates a null `AtomicPtr<T>`.
409 fn default() -> AtomicPtr<T> {
410 AtomicPtr::new(crate::ptr::null_mut())
411 }
412}
413
414#[cfg(target_has_atomic_load_store = "ptr")]
415#[stable(feature = "rust1", since = "1.0.0")]
416unsafe impl<T> Send for AtomicPtr<T> {}
417#[cfg(target_has_atomic_load_store = "ptr")]
418#[stable(feature = "rust1", since = "1.0.0")]
419unsafe impl<T> Sync for AtomicPtr<T> {}
420
421/// Atomic memory orderings
422///
423/// Memory orderings specify the way atomic operations synchronize memory.
424/// In its weakest [`Ordering::Relaxed`], only the memory directly touched by the
425/// operation is synchronized. On the other hand, a store-load pair of [`Ordering::SeqCst`]
426/// operations synchronize other memory while additionally preserving a total order of such
427/// operations across all threads.
428///
429/// Rust's memory orderings are [the same as those of
430/// C++20](https://en.cppreference.com/w/cpp/atomic/memory_order).
431///
432/// For more information see the [nomicon].
433///
434/// [nomicon]: ../../../nomicon/atomics.html
435#[stable(feature = "rust1", since = "1.0.0")]
436#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
437#[non_exhaustive]
438#[rustc_diagnostic_item = "Ordering"]
439pub enum Ordering {
440 /// No ordering constraints, only atomic operations.
441 ///
442 /// Corresponds to [`memory_order_relaxed`] in C++20.
443 ///
444 /// [`memory_order_relaxed`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering
445 #[stable(feature = "rust1", since = "1.0.0")]
446 Relaxed,
447 /// When coupled with a store, all previous operations become ordered
448 /// before any load of this value with [`Acquire`] (or stronger) ordering.
449 /// In particular, all previous writes become visible to all threads
450 /// that perform an [`Acquire`] (or stronger) load of this value.
451 ///
452 /// Notice that using this ordering for an operation that combines loads
453 /// and stores leads to a [`Relaxed`] load operation!
454 ///
455 /// This ordering is only applicable for operations that can perform a store.
456 ///
457 /// Corresponds to [`memory_order_release`] in C++20.
458 ///
459 /// [`memory_order_release`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
460 #[stable(feature = "rust1", since = "1.0.0")]
461 Release,
462 /// When coupled with a load, if the loaded value was written by a store operation with
463 /// [`Release`] (or stronger) ordering, then all subsequent operations
464 /// become ordered after that store. In particular, all subsequent loads will see data
465 /// written before the store.
466 ///
467 /// Notice that using this ordering for an operation that combines loads
468 /// and stores leads to a [`Relaxed`] store operation!
469 ///
470 /// This ordering is only applicable for operations that can perform a load.
471 ///
472 /// Corresponds to [`memory_order_acquire`] in C++20.
473 ///
474 /// [`memory_order_acquire`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
475 #[stable(feature = "rust1", since = "1.0.0")]
476 Acquire,
477 /// Has the effects of both [`Acquire`] and [`Release`] together:
478 /// For loads it uses [`Acquire`] ordering. For stores it uses the [`Release`] ordering.
479 ///
480 /// Notice that in the case of `compare_and_swap`, it is possible that the operation ends up
481 /// not performing any store and hence it has just [`Acquire`] ordering. However,
482 /// `AcqRel` will never perform [`Relaxed`] accesses.
483 ///
484 /// This ordering is only applicable for operations that combine both loads and stores.
485 ///
486 /// Corresponds to [`memory_order_acq_rel`] in C++20.
487 ///
488 /// [`memory_order_acq_rel`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
489 #[stable(feature = "rust1", since = "1.0.0")]
490 AcqRel,
491 /// Like [`Acquire`]/[`Release`]/[`AcqRel`] (for load, store, and load-with-store
492 /// operations, respectively) with the additional guarantee that all threads see all
493 /// sequentially consistent operations in the same order.
494 ///
495 /// Corresponds to [`memory_order_seq_cst`] in C++20.
496 ///
497 /// [`memory_order_seq_cst`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering
498 #[stable(feature = "rust1", since = "1.0.0")]
499 SeqCst,
500}
501
502/// An [`AtomicBool`] initialized to `false`.
503#[cfg(target_has_atomic_load_store = "8")]
504#[stable(feature = "rust1", since = "1.0.0")]
505#[deprecated(
506 since = "1.34.0",
507 note = "the `new` function is now preferred",
508 suggestion = "AtomicBool::new(false)"
509)]
510pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false);
511
512#[cfg(target_has_atomic_load_store = "8")]
513impl AtomicBool {
514 /// Creates a new `AtomicBool`.
515 ///
516 /// # Examples
517 ///
518 /// ```
519 /// use std::sync::atomic::AtomicBool;
520 ///
521 /// let atomic_true = AtomicBool::new(true);
522 /// let atomic_false = AtomicBool::new(false);
523 /// ```
524 #[inline]
525 #[stable(feature = "rust1", since = "1.0.0")]
526 #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
527 #[must_use]
528 pub const fn new(v: bool) -> AtomicBool {
529 AtomicBool { v: UnsafeCell::new(v as u8) }
530 }
531
532 /// Creates a new `AtomicBool` from a pointer.
533 ///
534 /// # Examples
535 ///
536 /// ```
537 /// use std::sync::atomic::{self, AtomicBool};
538 ///
539 /// // Get a pointer to an allocated value
540 /// let ptr: *mut bool = Box::into_raw(Box::new(false));
541 ///
542 /// assert!(ptr.cast::<AtomicBool>().is_aligned());
543 ///
544 /// {
545 /// // Create an atomic view of the allocated value
546 /// let atomic = unsafe { AtomicBool::from_ptr(ptr) };
547 ///
548 /// // Use `atomic` for atomic operations, possibly share it with other threads
549 /// atomic.store(true, atomic::Ordering::Relaxed);
550 /// }
551 ///
552 /// // It's ok to non-atomically access the value behind `ptr`,
553 /// // since the reference to the atomic ended its lifetime in the block above
554 /// assert_eq!(unsafe { *ptr }, true);
555 ///
556 /// // Deallocate the value
557 /// unsafe { drop(Box::from_raw(ptr)) }
558 /// ```
559 ///
560 /// # Safety
561 ///
562 /// * `ptr` must be aligned to `align_of::<AtomicBool>()` (note that this is always true, since
563 /// `align_of::<AtomicBool>() == 1`).
564 /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
565 /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
566 /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
567 /// sizes, without synchronization.
568 ///
569 /// [valid]: crate::ptr#safety
570 /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
571 #[inline]
572 #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
573 #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
574 pub const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBool {
575 // SAFETY: guaranteed by the caller
576 unsafe { &*ptr.cast() }
577 }
578
579 /// Returns a mutable reference to the underlying [`bool`].
580 ///
581 /// This is safe because the mutable reference guarantees that no other threads are
582 /// concurrently accessing the atomic data.
583 ///
584 /// # Examples
585 ///
586 /// ```
587 /// use std::sync::atomic::{AtomicBool, Ordering};
588 ///
589 /// let mut some_bool = AtomicBool::new(true);
590 /// assert_eq!(*some_bool.get_mut(), true);
591 /// *some_bool.get_mut() = false;
592 /// assert_eq!(some_bool.load(Ordering::SeqCst), false);
593 /// ```
594 #[inline]
595 #[stable(feature = "atomic_access", since = "1.15.0")]
596 pub fn get_mut(&mut self) -> &mut bool {
597 // SAFETY: the mutable reference guarantees unique ownership.
598 unsafe { &mut *(self.v.get() as *mut bool) }
599 }
600
601 /// Gets atomic access to a `&mut bool`.
602 ///
603 /// # Examples
604 ///
605 /// ```
606 /// #![feature(atomic_from_mut)]
607 /// use std::sync::atomic::{AtomicBool, Ordering};
608 ///
609 /// let mut some_bool = true;
610 /// let a = AtomicBool::from_mut(&mut some_bool);
611 /// a.store(false, Ordering::Relaxed);
612 /// assert_eq!(some_bool, false);
613 /// ```
614 #[inline]
615 #[cfg(target_has_atomic_equal_alignment = "8")]
616 #[unstable(feature = "atomic_from_mut", issue = "76314")]
617 pub fn from_mut(v: &mut bool) -> &mut Self {
618 // SAFETY: the mutable reference guarantees unique ownership, and
619 // alignment of both `bool` and `Self` is 1.
620 unsafe { &mut *(v as *mut bool as *mut Self) }
621 }
622
623 /// Gets non-atomic access to a `&mut [AtomicBool]` slice.
624 ///
625 /// This is safe because the mutable reference guarantees that no other threads are
626 /// concurrently accessing the atomic data.
627 ///
628 /// # Examples
629 ///
630 /// ```ignore-wasm
631 /// #![feature(atomic_from_mut)]
632 /// use std::sync::atomic::{AtomicBool, Ordering};
633 ///
634 /// let mut some_bools = [const { AtomicBool::new(false) }; 10];
635 ///
636 /// let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools);
637 /// assert_eq!(view, [false; 10]);
638 /// view[..5].copy_from_slice(&[true; 5]);
639 ///
640 /// std::thread::scope(|s| {
641 /// for t in &some_bools[..5] {
642 /// s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true));
643 /// }
644 ///
645 /// for f in &some_bools[5..] {
646 /// s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false));
647 /// }
648 /// });
649 /// ```
650 #[inline]
651 #[unstable(feature = "atomic_from_mut", issue = "76314")]
652 pub fn get_mut_slice(this: &mut [Self]) -> &mut [bool] {
653 // SAFETY: the mutable reference guarantees unique ownership.
654 unsafe { &mut *(this as *mut [Self] as *mut [bool]) }
655 }
656
657 /// Gets atomic access to a `&mut [bool]` slice.
658 ///
659 /// # Examples
660 ///
661 /// ```rust,ignore-wasm
662 /// #![feature(atomic_from_mut)]
663 /// use std::sync::atomic::{AtomicBool, Ordering};
664 ///
665 /// let mut some_bools = [false; 10];
666 /// let a = &*AtomicBool::from_mut_slice(&mut some_bools);
667 /// std::thread::scope(|s| {
668 /// for i in 0..a.len() {
669 /// s.spawn(move || a[i].store(true, Ordering::Relaxed));
670 /// }
671 /// });
672 /// assert_eq!(some_bools, [true; 10]);
673 /// ```
674 #[inline]
675 #[cfg(target_has_atomic_equal_alignment = "8")]
676 #[unstable(feature = "atomic_from_mut", issue = "76314")]
677 pub fn from_mut_slice(v: &mut [bool]) -> &mut [Self] {
678 // SAFETY: the mutable reference guarantees unique ownership, and
679 // alignment of both `bool` and `Self` is 1.
680 unsafe { &mut *(v as *mut [bool] as *mut [Self]) }
681 }
682
683 /// Consumes the atomic and returns the contained value.
684 ///
685 /// This is safe because passing `self` by value guarantees that no other threads are
686 /// concurrently accessing the atomic data.
687 ///
688 /// # Examples
689 ///
690 /// ```
691 /// use std::sync::atomic::AtomicBool;
692 ///
693 /// let some_bool = AtomicBool::new(true);
694 /// assert_eq!(some_bool.into_inner(), true);
695 /// ```
696 #[inline]
697 #[stable(feature = "atomic_access", since = "1.15.0")]
698 #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
699 pub const fn into_inner(self) -> bool {
700 self.v.into_inner() != 0
701 }
702
703 /// Loads a value from the bool.
704 ///
705 /// `load` takes an [`Ordering`] argument which describes the memory ordering
706 /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
707 ///
708 /// # Panics
709 ///
710 /// Panics if `order` is [`Release`] or [`AcqRel`].
711 ///
712 /// # Examples
713 ///
714 /// ```
715 /// use std::sync::atomic::{AtomicBool, Ordering};
716 ///
717 /// let some_bool = AtomicBool::new(true);
718 ///
719 /// assert_eq!(some_bool.load(Ordering::Relaxed), true);
720 /// ```
721 #[inline]
722 #[stable(feature = "rust1", since = "1.0.0")]
723 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
724 pub fn load(&self, order: Ordering) -> bool {
725 // SAFETY: any data races are prevented by atomic intrinsics and the raw
726 // pointer passed in is valid because we got it from a reference.
727 unsafe { atomic_load(self.v.get(), order) != 0 }
728 }
729
730 /// Stores a value into the bool.
731 ///
732 /// `store` takes an [`Ordering`] argument which describes the memory ordering
733 /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
734 ///
735 /// # Panics
736 ///
737 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
738 ///
739 /// # Examples
740 ///
741 /// ```
742 /// use std::sync::atomic::{AtomicBool, Ordering};
743 ///
744 /// let some_bool = AtomicBool::new(true);
745 ///
746 /// some_bool.store(false, Ordering::Relaxed);
747 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
748 /// ```
749 #[inline]
750 #[stable(feature = "rust1", since = "1.0.0")]
751 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
752 pub fn store(&self, val: bool, order: Ordering) {
753 // SAFETY: any data races are prevented by atomic intrinsics and the raw
754 // pointer passed in is valid because we got it from a reference.
755 unsafe {
756 atomic_store(self.v.get(), val as u8, order);
757 }
758 }
759
760 /// Stores a value into the bool, returning the previous value.
761 ///
762 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
763 /// of this operation. All ordering modes are possible. Note that using
764 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
765 /// using [`Release`] makes the load part [`Relaxed`].
766 ///
767 /// **Note:** This method is only available on platforms that support atomic
768 /// operations on `u8`.
769 ///
770 /// # Examples
771 ///
772 /// ```
773 /// use std::sync::atomic::{AtomicBool, Ordering};
774 ///
775 /// let some_bool = AtomicBool::new(true);
776 ///
777 /// assert_eq!(some_bool.swap(false, Ordering::Relaxed), true);
778 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
779 /// ```
780 #[inline]
781 #[stable(feature = "rust1", since = "1.0.0")]
782 #[cfg(target_has_atomic = "8")]
783 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
784 pub fn swap(&self, val: bool, order: Ordering) -> bool {
785 if EMULATE_ATOMIC_BOOL {
786 if val { self.fetch_or(true, order) } else { self.fetch_and(false, order) }
787 } else {
788 // SAFETY: data races are prevented by atomic intrinsics.
789 unsafe { atomic_swap(self.v.get(), val as u8, order) != 0 }
790 }
791 }
792
793 /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
794 ///
795 /// The return value is always the previous value. If it is equal to `current`, then the value
796 /// was updated.
797 ///
798 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
799 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
800 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
801 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
802 /// happens, and using [`Release`] makes the load part [`Relaxed`].
803 ///
804 /// **Note:** This method is only available on platforms that support atomic
805 /// operations on `u8`.
806 ///
807 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
808 ///
809 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
810 /// memory orderings:
811 ///
812 /// Original | Success | Failure
813 /// -------- | ------- | -------
814 /// Relaxed | Relaxed | Relaxed
815 /// Acquire | Acquire | Acquire
816 /// Release | Release | Relaxed
817 /// AcqRel | AcqRel | Acquire
818 /// SeqCst | SeqCst | SeqCst
819 ///
820 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
821 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
822 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
823 /// rather than to infer success vs failure based on the value that was read.
824 ///
825 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
826 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
827 /// which allows the compiler to generate better assembly code when the compare and swap
828 /// is used in a loop.
829 ///
830 /// # Examples
831 ///
832 /// ```
833 /// use std::sync::atomic::{AtomicBool, Ordering};
834 ///
835 /// let some_bool = AtomicBool::new(true);
836 ///
837 /// assert_eq!(some_bool.compare_and_swap(true, false, Ordering::Relaxed), true);
838 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
839 ///
840 /// assert_eq!(some_bool.compare_and_swap(true, true, Ordering::Relaxed), false);
841 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
842 /// ```
843 #[inline]
844 #[stable(feature = "rust1", since = "1.0.0")]
845 #[deprecated(
846 since = "1.50.0",
847 note = "Use `compare_exchange` or `compare_exchange_weak` instead"
848 )]
849 #[cfg(target_has_atomic = "8")]
850 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
851 pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool {
852 match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
853 Ok(x) => x,
854 Err(x) => x,
855 }
856 }
857
858 /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
859 ///
860 /// The return value is a result indicating whether the new value was written and containing
861 /// the previous value. On success this value is guaranteed to be equal to `current`.
862 ///
863 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
864 /// ordering of this operation. `success` describes the required ordering for the
865 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
866 /// `failure` describes the required ordering for the load operation that takes place when
867 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
868 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
869 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
870 ///
871 /// **Note:** This method is only available on platforms that support atomic
872 /// operations on `u8`.
873 ///
874 /// # Examples
875 ///
876 /// ```
877 /// use std::sync::atomic::{AtomicBool, Ordering};
878 ///
879 /// let some_bool = AtomicBool::new(true);
880 ///
881 /// assert_eq!(some_bool.compare_exchange(true,
882 /// false,
883 /// Ordering::Acquire,
884 /// Ordering::Relaxed),
885 /// Ok(true));
886 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
887 ///
888 /// assert_eq!(some_bool.compare_exchange(true, true,
889 /// Ordering::SeqCst,
890 /// Ordering::Acquire),
891 /// Err(false));
892 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
893 /// ```
894 ///
895 /// # Considerations
896 ///
897 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
898 /// of CAS operations. In particular, a load of the value followed by a successful
899 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
900 /// changed the value in the interim. This is usually important when the *equality* check in
901 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
902 /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the
903 /// [ABA problem].
904 ///
905 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
906 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
907 #[inline]
908 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
909 #[doc(alias = "compare_and_swap")]
910 #[cfg(target_has_atomic = "8")]
911 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
912 pub fn compare_exchange(
913 &self,
914 current: bool,
915 new: bool,
916 success: Ordering,
917 failure: Ordering,
918 ) -> Result<bool, bool> {
919 if EMULATE_ATOMIC_BOOL {
920 // Pick the strongest ordering from success and failure.
921 let order = match (success, failure) {
922 (SeqCst, _) => SeqCst,
923 (_, SeqCst) => SeqCst,
924 (AcqRel, _) => AcqRel,
925 (_, AcqRel) => {
926 panic!("there is no such thing as an acquire-release failure ordering")
927 }
928 (Release, Acquire) => AcqRel,
929 (Acquire, _) => Acquire,
930 (_, Acquire) => Acquire,
931 (Release, Relaxed) => Release,
932 (_, Release) => panic!("there is no such thing as a release failure ordering"),
933 (Relaxed, Relaxed) => Relaxed,
934 };
935 let old = if current == new {
936 // This is a no-op, but we still need to perform the operation
937 // for memory ordering reasons.
938 self.fetch_or(false, order)
939 } else {
940 // This sets the value to the new one and returns the old one.
941 self.swap(new, order)
942 };
943 if old == current { Ok(old) } else { Err(old) }
944 } else {
945 // SAFETY: data races are prevented by atomic intrinsics.
946 match unsafe {
947 atomic_compare_exchange(self.v.get(), current as u8, new as u8, success, failure)
948 } {
949 Ok(x) => Ok(x != 0),
950 Err(x) => Err(x != 0),
951 }
952 }
953 }
954
955 /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
956 ///
957 /// Unlike [`AtomicBool::compare_exchange`], this function is allowed to spuriously fail even when the
958 /// comparison succeeds, which can result in more efficient code on some platforms. The
959 /// return value is a result indicating whether the new value was written and containing the
960 /// previous value.
961 ///
962 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
963 /// ordering of this operation. `success` describes the required ordering for the
964 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
965 /// `failure` describes the required ordering for the load operation that takes place when
966 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
967 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
968 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
969 ///
970 /// **Note:** This method is only available on platforms that support atomic
971 /// operations on `u8`.
972 ///
973 /// # Examples
974 ///
975 /// ```
976 /// use std::sync::atomic::{AtomicBool, Ordering};
977 ///
978 /// let val = AtomicBool::new(false);
979 ///
980 /// let new = true;
981 /// let mut old = val.load(Ordering::Relaxed);
982 /// loop {
983 /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
984 /// Ok(_) => break,
985 /// Err(x) => old = x,
986 /// }
987 /// }
988 /// ```
989 ///
990 /// # Considerations
991 ///
992 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
993 /// of CAS operations. In particular, a load of the value followed by a successful
994 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
995 /// changed the value in the interim. This is usually important when the *equality* check in
996 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
997 /// does not necessarily imply identity. In this case, `compare_exchange` can lead to the
998 /// [ABA problem].
999 ///
1000 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1001 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1002 #[inline]
1003 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1004 #[doc(alias = "compare_and_swap")]
1005 #[cfg(target_has_atomic = "8")]
1006 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1007 pub fn compare_exchange_weak(
1008 &self,
1009 current: bool,
1010 new: bool,
1011 success: Ordering,
1012 failure: Ordering,
1013 ) -> Result<bool, bool> {
1014 if EMULATE_ATOMIC_BOOL {
1015 return self.compare_exchange(current, new, success, failure);
1016 }
1017
1018 // SAFETY: data races are prevented by atomic intrinsics.
1019 match unsafe {
1020 atomic_compare_exchange_weak(self.v.get(), current as u8, new as u8, success, failure)
1021 } {
1022 Ok(x) => Ok(x != 0),
1023 Err(x) => Err(x != 0),
1024 }
1025 }
1026
1027 /// Logical "and" with a boolean value.
1028 ///
1029 /// Performs a logical "and" operation on the current value and the argument `val`, and sets
1030 /// the new value to the result.
1031 ///
1032 /// Returns the previous value.
1033 ///
1034 /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
1035 /// of this operation. All ordering modes are possible. Note that using
1036 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1037 /// using [`Release`] makes the load part [`Relaxed`].
1038 ///
1039 /// **Note:** This method is only available on platforms that support atomic
1040 /// operations on `u8`.
1041 ///
1042 /// # Examples
1043 ///
1044 /// ```
1045 /// use std::sync::atomic::{AtomicBool, Ordering};
1046 ///
1047 /// let foo = AtomicBool::new(true);
1048 /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), true);
1049 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1050 ///
1051 /// let foo = AtomicBool::new(true);
1052 /// assert_eq!(foo.fetch_and(true, Ordering::SeqCst), true);
1053 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1054 ///
1055 /// let foo = AtomicBool::new(false);
1056 /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), false);
1057 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1058 /// ```
1059 #[inline]
1060 #[stable(feature = "rust1", since = "1.0.0")]
1061 #[cfg(target_has_atomic = "8")]
1062 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1063 pub fn fetch_and(&self, val: bool, order: Ordering) -> bool {
1064 // SAFETY: data races are prevented by atomic intrinsics.
1065 unsafe { atomic_and(self.v.get(), val as u8, order) != 0 }
1066 }
1067
1068 /// Logical "nand" with a boolean value.
1069 ///
1070 /// Performs a logical "nand" operation on the current value and the argument `val`, and sets
1071 /// the new value to the result.
1072 ///
1073 /// Returns the previous value.
1074 ///
1075 /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
1076 /// of this operation. All ordering modes are possible. Note that using
1077 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1078 /// using [`Release`] makes the load part [`Relaxed`].
1079 ///
1080 /// **Note:** This method is only available on platforms that support atomic
1081 /// operations on `u8`.
1082 ///
1083 /// # Examples
1084 ///
1085 /// ```
1086 /// use std::sync::atomic::{AtomicBool, Ordering};
1087 ///
1088 /// let foo = AtomicBool::new(true);
1089 /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), true);
1090 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1091 ///
1092 /// let foo = AtomicBool::new(true);
1093 /// assert_eq!(foo.fetch_nand(true, Ordering::SeqCst), true);
1094 /// assert_eq!(foo.load(Ordering::SeqCst) as usize, 0);
1095 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1096 ///
1097 /// let foo = AtomicBool::new(false);
1098 /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), false);
1099 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1100 /// ```
1101 #[inline]
1102 #[stable(feature = "rust1", since = "1.0.0")]
1103 #[cfg(target_has_atomic = "8")]
1104 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1105 pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool {
1106 // We can't use atomic_nand here because it can result in a bool with
1107 // an invalid value. This happens because the atomic operation is done
1108 // with an 8-bit integer internally, which would set the upper 7 bits.
1109 // So we just use fetch_xor or swap instead.
1110 if val {
1111 // !(x & true) == !x
1112 // We must invert the bool.
1113 self.fetch_xor(true, order)
1114 } else {
1115 // !(x & false) == true
1116 // We must set the bool to true.
1117 self.swap(true, order)
1118 }
1119 }
1120
1121 /// Logical "or" with a boolean value.
1122 ///
1123 /// Performs a logical "or" operation on the current value and the argument `val`, and sets the
1124 /// new value to the result.
1125 ///
1126 /// Returns the previous value.
1127 ///
1128 /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
1129 /// of this operation. All ordering modes are possible. Note that using
1130 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1131 /// using [`Release`] makes the load part [`Relaxed`].
1132 ///
1133 /// **Note:** This method is only available on platforms that support atomic
1134 /// operations on `u8`.
1135 ///
1136 /// # Examples
1137 ///
1138 /// ```
1139 /// use std::sync::atomic::{AtomicBool, Ordering};
1140 ///
1141 /// let foo = AtomicBool::new(true);
1142 /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), true);
1143 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1144 ///
1145 /// let foo = AtomicBool::new(true);
1146 /// assert_eq!(foo.fetch_or(true, Ordering::SeqCst), true);
1147 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1148 ///
1149 /// let foo = AtomicBool::new(false);
1150 /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), false);
1151 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1152 /// ```
1153 #[inline]
1154 #[stable(feature = "rust1", since = "1.0.0")]
1155 #[cfg(target_has_atomic = "8")]
1156 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1157 pub fn fetch_or(&self, val: bool, order: Ordering) -> bool {
1158 // SAFETY: data races are prevented by atomic intrinsics.
1159 unsafe { atomic_or(self.v.get(), val as u8, order) != 0 }
1160 }
1161
1162 /// Logical "xor" with a boolean value.
1163 ///
1164 /// Performs a logical "xor" operation on the current value and the argument `val`, and sets
1165 /// the new value to the result.
1166 ///
1167 /// Returns the previous value.
1168 ///
1169 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
1170 /// of this operation. All ordering modes are possible. Note that using
1171 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1172 /// using [`Release`] makes the load part [`Relaxed`].
1173 ///
1174 /// **Note:** This method is only available on platforms that support atomic
1175 /// operations on `u8`.
1176 ///
1177 /// # Examples
1178 ///
1179 /// ```
1180 /// use std::sync::atomic::{AtomicBool, Ordering};
1181 ///
1182 /// let foo = AtomicBool::new(true);
1183 /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), true);
1184 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1185 ///
1186 /// let foo = AtomicBool::new(true);
1187 /// assert_eq!(foo.fetch_xor(true, Ordering::SeqCst), true);
1188 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1189 ///
1190 /// let foo = AtomicBool::new(false);
1191 /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), false);
1192 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1193 /// ```
1194 #[inline]
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 #[cfg(target_has_atomic = "8")]
1197 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1198 pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool {
1199 // SAFETY: data races are prevented by atomic intrinsics.
1200 unsafe { atomic_xor(self.v.get(), val as u8, order) != 0 }
1201 }
1202
1203 /// Logical "not" with a boolean value.
1204 ///
1205 /// Performs a logical "not" operation on the current value, and sets
1206 /// the new value to the result.
1207 ///
1208 /// Returns the previous value.
1209 ///
1210 /// `fetch_not` takes an [`Ordering`] argument which describes the memory ordering
1211 /// of this operation. All ordering modes are possible. Note that using
1212 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1213 /// using [`Release`] makes the load part [`Relaxed`].
1214 ///
1215 /// **Note:** This method is only available on platforms that support atomic
1216 /// operations on `u8`.
1217 ///
1218 /// # Examples
1219 ///
1220 /// ```
1221 /// use std::sync::atomic::{AtomicBool, Ordering};
1222 ///
1223 /// let foo = AtomicBool::new(true);
1224 /// assert_eq!(foo.fetch_not(Ordering::SeqCst), true);
1225 /// assert_eq!(foo.load(Ordering::SeqCst), false);
1226 ///
1227 /// let foo = AtomicBool::new(false);
1228 /// assert_eq!(foo.fetch_not(Ordering::SeqCst), false);
1229 /// assert_eq!(foo.load(Ordering::SeqCst), true);
1230 /// ```
1231 #[inline]
1232 #[stable(feature = "atomic_bool_fetch_not", since = "1.81.0")]
1233 #[cfg(target_has_atomic = "8")]
1234 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1235 pub fn fetch_not(&self, order: Ordering) -> bool {
1236 self.fetch_xor(true, order)
1237 }
1238
1239 /// Returns a mutable pointer to the underlying [`bool`].
1240 ///
1241 /// Doing non-atomic reads and writes on the resulting boolean can be a data race.
1242 /// This method is mostly useful for FFI, where the function signature may use
1243 /// `*mut bool` instead of `&AtomicBool`.
1244 ///
1245 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
1246 /// atomic types work with interior mutability. All modifications of an atomic change the value
1247 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
1248 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
1249 /// requirements of the [memory model].
1250 ///
1251 /// # Examples
1252 ///
1253 /// ```ignore (extern-declaration)
1254 /// # fn main() {
1255 /// use std::sync::atomic::AtomicBool;
1256 ///
1257 /// extern "C" {
1258 /// fn my_atomic_op(arg: *mut bool);
1259 /// }
1260 ///
1261 /// let mut atomic = AtomicBool::new(true);
1262 /// unsafe {
1263 /// my_atomic_op(atomic.as_ptr());
1264 /// }
1265 /// # }
1266 /// ```
1267 ///
1268 /// [memory model]: self#memory-model-for-atomic-accesses
1269 #[inline]
1270 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
1271 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
1272 #[rustc_never_returns_null_ptr]
1273 pub const fn as_ptr(&self) -> *mut bool {
1274 self.v.get().cast()
1275 }
1276
1277 /// Fetches the value, and applies a function to it that returns an optional
1278 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1279 /// returned `Some(_)`, else `Err(previous_value)`.
1280 ///
1281 /// Note: This may call the function multiple times if the value has been
1282 /// changed from other threads in the meantime, as long as the function
1283 /// returns `Some(_)`, but the function will have been applied only once to
1284 /// the stored value.
1285 ///
1286 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
1287 /// ordering of this operation. The first describes the required ordering for
1288 /// when the operation finally succeeds while the second describes the
1289 /// required ordering for loads. These correspond to the success and failure
1290 /// orderings of [`AtomicBool::compare_exchange`] respectively.
1291 ///
1292 /// Using [`Acquire`] as success ordering makes the store part of this
1293 /// operation [`Relaxed`], and using [`Release`] makes the final successful
1294 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1295 /// [`Acquire`] or [`Relaxed`].
1296 ///
1297 /// **Note:** This method is only available on platforms that support atomic
1298 /// operations on `u8`.
1299 ///
1300 /// # Considerations
1301 ///
1302 /// This method is not magic; it is not provided by the hardware, and does not act like a
1303 /// critical section or mutex.
1304 ///
1305 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1306 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
1307 ///
1308 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1309 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1310 ///
1311 /// # Examples
1312 ///
1313 /// ```rust
1314 /// use std::sync::atomic::{AtomicBool, Ordering};
1315 ///
1316 /// let x = AtomicBool::new(false);
1317 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
1318 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
1319 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
1320 /// assert_eq!(x.load(Ordering::SeqCst), false);
1321 /// ```
1322 #[inline]
1323 #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
1324 #[cfg(target_has_atomic = "8")]
1325 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1326 pub fn fetch_update<F>(
1327 &self,
1328 set_order: Ordering,
1329 fetch_order: Ordering,
1330 mut f: F,
1331 ) -> Result<bool, bool>
1332 where
1333 F: FnMut(bool) -> Option<bool>,
1334 {
1335 let mut prev = self.load(fetch_order);
1336 while let Some(next) = f(prev) {
1337 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
1338 x @ Ok(_) => return x,
1339 Err(next_prev) => prev = next_prev,
1340 }
1341 }
1342 Err(prev)
1343 }
1344
1345 /// Fetches the value, and applies a function to it that returns an optional
1346 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1347 /// returned `Some(_)`, else `Err(previous_value)`.
1348 ///
1349 /// See also: [`update`](`AtomicBool::update`).
1350 ///
1351 /// Note: This may call the function multiple times if the value has been
1352 /// changed from other threads in the meantime, as long as the function
1353 /// returns `Some(_)`, but the function will have been applied only once to
1354 /// the stored value.
1355 ///
1356 /// `try_update` takes two [`Ordering`] arguments to describe the memory
1357 /// ordering of this operation. The first describes the required ordering for
1358 /// when the operation finally succeeds while the second describes the
1359 /// required ordering for loads. These correspond to the success and failure
1360 /// orderings of [`AtomicBool::compare_exchange`] respectively.
1361 ///
1362 /// Using [`Acquire`] as success ordering makes the store part of this
1363 /// operation [`Relaxed`], and using [`Release`] makes the final successful
1364 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1365 /// [`Acquire`] or [`Relaxed`].
1366 ///
1367 /// **Note:** This method is only available on platforms that support atomic
1368 /// operations on `u8`.
1369 ///
1370 /// # Considerations
1371 ///
1372 /// This method is not magic; it is not provided by the hardware, and does not act like a
1373 /// critical section or mutex.
1374 ///
1375 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1376 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
1377 ///
1378 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1379 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1380 ///
1381 /// # Examples
1382 ///
1383 /// ```rust
1384 /// #![feature(atomic_try_update)]
1385 /// use std::sync::atomic::{AtomicBool, Ordering};
1386 ///
1387 /// let x = AtomicBool::new(false);
1388 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
1389 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
1390 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
1391 /// assert_eq!(x.load(Ordering::SeqCst), false);
1392 /// ```
1393 #[inline]
1394 #[unstable(feature = "atomic_try_update", issue = "135894")]
1395 #[cfg(target_has_atomic = "8")]
1396 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1397 pub fn try_update(
1398 &self,
1399 set_order: Ordering,
1400 fetch_order: Ordering,
1401 f: impl FnMut(bool) -> Option<bool>,
1402 ) -> Result<bool, bool> {
1403 // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
1404 // when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
1405 self.fetch_update(set_order, fetch_order, f)
1406 }
1407
1408 /// Fetches the value, applies a function to it that it return a new value.
1409 /// The new value is stored and the old value is returned.
1410 ///
1411 /// See also: [`try_update`](`AtomicBool::try_update`).
1412 ///
1413 /// Note: This may call the function multiple times if the value has been changed from other threads in
1414 /// the meantime, but the function will have been applied only once to the stored value.
1415 ///
1416 /// `update` takes two [`Ordering`] arguments to describe the memory
1417 /// ordering of this operation. The first describes the required ordering for
1418 /// when the operation finally succeeds while the second describes the
1419 /// required ordering for loads. These correspond to the success and failure
1420 /// orderings of [`AtomicBool::compare_exchange`] respectively.
1421 ///
1422 /// Using [`Acquire`] as success ordering makes the store part
1423 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
1424 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1425 ///
1426 /// **Note:** This method is only available on platforms that support atomic operations on `u8`.
1427 ///
1428 /// # Considerations
1429 ///
1430 /// This method is not magic; it is not provided by the hardware, and does not act like a
1431 /// critical section or mutex.
1432 ///
1433 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1434 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem].
1435 ///
1436 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1437 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1438 ///
1439 /// # Examples
1440 ///
1441 /// ```rust
1442 /// #![feature(atomic_try_update)]
1443 ///
1444 /// use std::sync::atomic::{AtomicBool, Ordering};
1445 ///
1446 /// let x = AtomicBool::new(false);
1447 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), false);
1448 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| !x), true);
1449 /// assert_eq!(x.load(Ordering::SeqCst), false);
1450 /// ```
1451 #[inline]
1452 #[unstable(feature = "atomic_try_update", issue = "135894")]
1453 #[cfg(target_has_atomic = "8")]
1454 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1455 pub fn update(
1456 &self,
1457 set_order: Ordering,
1458 fetch_order: Ordering,
1459 mut f: impl FnMut(bool) -> bool,
1460 ) -> bool {
1461 let mut prev = self.load(fetch_order);
1462 loop {
1463 match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
1464 Ok(x) => break x,
1465 Err(next_prev) => prev = next_prev,
1466 }
1467 }
1468 }
1469}
1470
1471#[cfg(target_has_atomic_load_store = "ptr")]
1472impl<T> AtomicPtr<T> {
1473 /// Creates a new `AtomicPtr`.
1474 ///
1475 /// # Examples
1476 ///
1477 /// ```
1478 /// use std::sync::atomic::AtomicPtr;
1479 ///
1480 /// let ptr = &mut 5;
1481 /// let atomic_ptr = AtomicPtr::new(ptr);
1482 /// ```
1483 #[inline]
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
1486 pub const fn new(p: *mut T) -> AtomicPtr<T> {
1487 AtomicPtr { p: UnsafeCell::new(p) }
1488 }
1489
1490 /// Creates a new `AtomicPtr` from a pointer.
1491 ///
1492 /// # Examples
1493 ///
1494 /// ```
1495 /// use std::sync::atomic::{self, AtomicPtr};
1496 ///
1497 /// // Get a pointer to an allocated value
1498 /// let ptr: *mut *mut u8 = Box::into_raw(Box::new(std::ptr::null_mut()));
1499 ///
1500 /// assert!(ptr.cast::<AtomicPtr<u8>>().is_aligned());
1501 ///
1502 /// {
1503 /// // Create an atomic view of the allocated value
1504 /// let atomic = unsafe { AtomicPtr::from_ptr(ptr) };
1505 ///
1506 /// // Use `atomic` for atomic operations, possibly share it with other threads
1507 /// atomic.store(std::ptr::NonNull::dangling().as_ptr(), atomic::Ordering::Relaxed);
1508 /// }
1509 ///
1510 /// // It's ok to non-atomically access the value behind `ptr`,
1511 /// // since the reference to the atomic ended its lifetime in the block above
1512 /// assert!(!unsafe { *ptr }.is_null());
1513 ///
1514 /// // Deallocate the value
1515 /// unsafe { drop(Box::from_raw(ptr)) }
1516 /// ```
1517 ///
1518 /// # Safety
1519 ///
1520 /// * `ptr` must be aligned to `align_of::<AtomicPtr<T>>()` (note that on some platforms this
1521 /// can be bigger than `align_of::<*mut T>()`).
1522 /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
1523 /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
1524 /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
1525 /// sizes, without synchronization.
1526 ///
1527 /// [valid]: crate::ptr#safety
1528 /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
1529 #[inline]
1530 #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
1531 #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
1532 pub const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr<T> {
1533 // SAFETY: guaranteed by the caller
1534 unsafe { &*ptr.cast() }
1535 }
1536
1537 /// Returns a mutable reference to the underlying pointer.
1538 ///
1539 /// This is safe because the mutable reference guarantees that no other threads are
1540 /// concurrently accessing the atomic data.
1541 ///
1542 /// # Examples
1543 ///
1544 /// ```
1545 /// use std::sync::atomic::{AtomicPtr, Ordering};
1546 ///
1547 /// let mut data = 10;
1548 /// let mut atomic_ptr = AtomicPtr::new(&mut data);
1549 /// let mut other_data = 5;
1550 /// *atomic_ptr.get_mut() = &mut other_data;
1551 /// assert_eq!(unsafe { *atomic_ptr.load(Ordering::SeqCst) }, 5);
1552 /// ```
1553 #[inline]
1554 #[stable(feature = "atomic_access", since = "1.15.0")]
1555 pub fn get_mut(&mut self) -> &mut *mut T {
1556 self.p.get_mut()
1557 }
1558
1559 /// Gets atomic access to a pointer.
1560 ///
1561 /// **Note:** This function is only available on targets where `AtomicPtr<T>` has the same alignment as `*const T`
1562 ///
1563 /// # Examples
1564 ///
1565 /// ```
1566 /// #![feature(atomic_from_mut)]
1567 /// use std::sync::atomic::{AtomicPtr, Ordering};
1568 ///
1569 /// let mut data = 123;
1570 /// let mut some_ptr = &mut data as *mut i32;
1571 /// let a = AtomicPtr::from_mut(&mut some_ptr);
1572 /// let mut other_data = 456;
1573 /// a.store(&mut other_data, Ordering::Relaxed);
1574 /// assert_eq!(unsafe { *some_ptr }, 456);
1575 /// ```
1576 #[inline]
1577 #[cfg(target_has_atomic_equal_alignment = "ptr")]
1578 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1579 pub fn from_mut(v: &mut *mut T) -> &mut Self {
1580 let [] = [(); align_of::<AtomicPtr<()>>() - align_of::<*mut ()>()];
1581 // SAFETY:
1582 // - the mutable reference guarantees unique ownership.
1583 // - the alignment of `*mut T` and `Self` is the same on all platforms
1584 // supported by rust, as verified above.
1585 unsafe { &mut *(v as *mut *mut T as *mut Self) }
1586 }
1587
1588 /// Gets non-atomic access to a `&mut [AtomicPtr]` slice.
1589 ///
1590 /// This is safe because the mutable reference guarantees that no other threads are
1591 /// concurrently accessing the atomic data.
1592 ///
1593 /// # Examples
1594 ///
1595 /// ```ignore-wasm
1596 /// #![feature(atomic_from_mut)]
1597 /// use std::ptr::null_mut;
1598 /// use std::sync::atomic::{AtomicPtr, Ordering};
1599 ///
1600 /// let mut some_ptrs = [const { AtomicPtr::new(null_mut::<String>()) }; 10];
1601 ///
1602 /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs);
1603 /// assert_eq!(view, [null_mut::<String>(); 10]);
1604 /// view
1605 /// .iter_mut()
1606 /// .enumerate()
1607 /// .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}"))));
1608 ///
1609 /// std::thread::scope(|s| {
1610 /// for ptr in &some_ptrs {
1611 /// s.spawn(move || {
1612 /// let ptr = ptr.load(Ordering::Relaxed);
1613 /// assert!(!ptr.is_null());
1614 ///
1615 /// let name = unsafe { Box::from_raw(ptr) };
1616 /// println!("Hello, {name}!");
1617 /// });
1618 /// }
1619 /// });
1620 /// ```
1621 #[inline]
1622 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1623 pub fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T] {
1624 // SAFETY: the mutable reference guarantees unique ownership.
1625 unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) }
1626 }
1627
1628 /// Gets atomic access to a slice of pointers.
1629 ///
1630 /// **Note:** This function is only available on targets where `AtomicPtr<T>` has the same alignment as `*const T`
1631 ///
1632 /// # Examples
1633 ///
1634 /// ```ignore-wasm
1635 /// #![feature(atomic_from_mut)]
1636 /// use std::ptr::null_mut;
1637 /// use std::sync::atomic::{AtomicPtr, Ordering};
1638 ///
1639 /// let mut some_ptrs = [null_mut::<String>(); 10];
1640 /// let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs);
1641 /// std::thread::scope(|s| {
1642 /// for i in 0..a.len() {
1643 /// s.spawn(move || {
1644 /// let name = Box::new(format!("thread{i}"));
1645 /// a[i].store(Box::into_raw(name), Ordering::Relaxed);
1646 /// });
1647 /// }
1648 /// });
1649 /// for p in some_ptrs {
1650 /// assert!(!p.is_null());
1651 /// let name = unsafe { Box::from_raw(p) };
1652 /// println!("Hello, {name}!");
1653 /// }
1654 /// ```
1655 #[inline]
1656 #[cfg(target_has_atomic_equal_alignment = "ptr")]
1657 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1658 pub fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self] {
1659 // SAFETY:
1660 // - the mutable reference guarantees unique ownership.
1661 // - the alignment of `*mut T` and `Self` is the same on all platforms
1662 // supported by rust, as verified above.
1663 unsafe { &mut *(v as *mut [*mut T] as *mut [Self]) }
1664 }
1665
1666 /// Consumes the atomic and returns the contained value.
1667 ///
1668 /// This is safe because passing `self` by value guarantees that no other threads are
1669 /// concurrently accessing the atomic data.
1670 ///
1671 /// # Examples
1672 ///
1673 /// ```
1674 /// use std::sync::atomic::AtomicPtr;
1675 ///
1676 /// let mut data = 5;
1677 /// let atomic_ptr = AtomicPtr::new(&mut data);
1678 /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5);
1679 /// ```
1680 #[inline]
1681 #[stable(feature = "atomic_access", since = "1.15.0")]
1682 #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
1683 pub const fn into_inner(self) -> *mut T {
1684 self.p.into_inner()
1685 }
1686
1687 /// Loads a value from the pointer.
1688 ///
1689 /// `load` takes an [`Ordering`] argument which describes the memory ordering
1690 /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
1691 ///
1692 /// # Panics
1693 ///
1694 /// Panics if `order` is [`Release`] or [`AcqRel`].
1695 ///
1696 /// # Examples
1697 ///
1698 /// ```
1699 /// use std::sync::atomic::{AtomicPtr, Ordering};
1700 ///
1701 /// let ptr = &mut 5;
1702 /// let some_ptr = AtomicPtr::new(ptr);
1703 ///
1704 /// let value = some_ptr.load(Ordering::Relaxed);
1705 /// ```
1706 #[inline]
1707 #[stable(feature = "rust1", since = "1.0.0")]
1708 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1709 pub fn load(&self, order: Ordering) -> *mut T {
1710 // SAFETY: data races are prevented by atomic intrinsics.
1711 unsafe { atomic_load(self.p.get(), order) }
1712 }
1713
1714 /// Stores a value into the pointer.
1715 ///
1716 /// `store` takes an [`Ordering`] argument which describes the memory ordering
1717 /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
1718 ///
1719 /// # Panics
1720 ///
1721 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
1722 ///
1723 /// # Examples
1724 ///
1725 /// ```
1726 /// use std::sync::atomic::{AtomicPtr, Ordering};
1727 ///
1728 /// let ptr = &mut 5;
1729 /// let some_ptr = AtomicPtr::new(ptr);
1730 ///
1731 /// let other_ptr = &mut 10;
1732 ///
1733 /// some_ptr.store(other_ptr, Ordering::Relaxed);
1734 /// ```
1735 #[inline]
1736 #[stable(feature = "rust1", since = "1.0.0")]
1737 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1738 pub fn store(&self, ptr: *mut T, order: Ordering) {
1739 // SAFETY: data races are prevented by atomic intrinsics.
1740 unsafe {
1741 atomic_store(self.p.get(), ptr, order);
1742 }
1743 }
1744
1745 /// Stores a value into the pointer, returning the previous value.
1746 ///
1747 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
1748 /// of this operation. All ordering modes are possible. Note that using
1749 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1750 /// using [`Release`] makes the load part [`Relaxed`].
1751 ///
1752 /// **Note:** This method is only available on platforms that support atomic
1753 /// operations on pointers.
1754 ///
1755 /// # Examples
1756 ///
1757 /// ```
1758 /// use std::sync::atomic::{AtomicPtr, Ordering};
1759 ///
1760 /// let ptr = &mut 5;
1761 /// let some_ptr = AtomicPtr::new(ptr);
1762 ///
1763 /// let other_ptr = &mut 10;
1764 ///
1765 /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed);
1766 /// ```
1767 #[inline]
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 #[cfg(target_has_atomic = "ptr")]
1770 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1771 pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T {
1772 // SAFETY: data races are prevented by atomic intrinsics.
1773 unsafe { atomic_swap(self.p.get(), ptr, order) }
1774 }
1775
1776 /// Stores a value into the pointer if the current value is the same as the `current` value.
1777 ///
1778 /// The return value is always the previous value. If it is equal to `current`, then the value
1779 /// was updated.
1780 ///
1781 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
1782 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
1783 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
1784 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
1785 /// happens, and using [`Release`] makes the load part [`Relaxed`].
1786 ///
1787 /// **Note:** This method is only available on platforms that support atomic
1788 /// operations on pointers.
1789 ///
1790 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
1791 ///
1792 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
1793 /// memory orderings:
1794 ///
1795 /// Original | Success | Failure
1796 /// -------- | ------- | -------
1797 /// Relaxed | Relaxed | Relaxed
1798 /// Acquire | Acquire | Acquire
1799 /// Release | Release | Relaxed
1800 /// AcqRel | AcqRel | Acquire
1801 /// SeqCst | SeqCst | SeqCst
1802 ///
1803 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
1804 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
1805 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
1806 /// rather than to infer success vs failure based on the value that was read.
1807 ///
1808 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
1809 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
1810 /// which allows the compiler to generate better assembly code when the compare and swap
1811 /// is used in a loop.
1812 ///
1813 /// # Examples
1814 ///
1815 /// ```
1816 /// use std::sync::atomic::{AtomicPtr, Ordering};
1817 ///
1818 /// let ptr = &mut 5;
1819 /// let some_ptr = AtomicPtr::new(ptr);
1820 ///
1821 /// let other_ptr = &mut 10;
1822 ///
1823 /// let value = some_ptr.compare_and_swap(ptr, other_ptr, Ordering::Relaxed);
1824 /// ```
1825 #[inline]
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 #[deprecated(
1828 since = "1.50.0",
1829 note = "Use `compare_exchange` or `compare_exchange_weak` instead"
1830 )]
1831 #[cfg(target_has_atomic = "ptr")]
1832 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1833 pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
1834 match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
1835 Ok(x) => x,
1836 Err(x) => x,
1837 }
1838 }
1839
1840 /// Stores a value into the pointer if the current value is the same as the `current` value.
1841 ///
1842 /// The return value is a result indicating whether the new value was written and containing
1843 /// the previous value. On success this value is guaranteed to be equal to `current`.
1844 ///
1845 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
1846 /// ordering of this operation. `success` describes the required ordering for the
1847 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1848 /// `failure` describes the required ordering for the load operation that takes place when
1849 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1850 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1851 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1852 ///
1853 /// **Note:** This method is only available on platforms that support atomic
1854 /// operations on pointers.
1855 ///
1856 /// # Examples
1857 ///
1858 /// ```
1859 /// use std::sync::atomic::{AtomicPtr, Ordering};
1860 ///
1861 /// let ptr = &mut 5;
1862 /// let some_ptr = AtomicPtr::new(ptr);
1863 ///
1864 /// let other_ptr = &mut 10;
1865 ///
1866 /// let value = some_ptr.compare_exchange(ptr, other_ptr,
1867 /// Ordering::SeqCst, Ordering::Relaxed);
1868 /// ```
1869 ///
1870 /// # Considerations
1871 ///
1872 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1873 /// of CAS operations. In particular, a load of the value followed by a successful
1874 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1875 /// changed the value in the interim. This is usually important when the *equality* check in
1876 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1877 /// does not necessarily imply identity. This is a particularly common case for pointers, as
1878 /// a pointer holding the same address does not imply that the same object exists at that
1879 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
1880 ///
1881 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1882 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1883 #[inline]
1884 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1885 #[cfg(target_has_atomic = "ptr")]
1886 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1887 pub fn compare_exchange(
1888 &self,
1889 current: *mut T,
1890 new: *mut T,
1891 success: Ordering,
1892 failure: Ordering,
1893 ) -> Result<*mut T, *mut T> {
1894 // SAFETY: data races are prevented by atomic intrinsics.
1895 unsafe { atomic_compare_exchange(self.p.get(), current, new, success, failure) }
1896 }
1897
1898 /// Stores a value into the pointer if the current value is the same as the `current` value.
1899 ///
1900 /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the
1901 /// comparison succeeds, which can result in more efficient code on some platforms. The
1902 /// return value is a result indicating whether the new value was written and containing the
1903 /// previous value.
1904 ///
1905 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
1906 /// ordering of this operation. `success` describes the required ordering for the
1907 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1908 /// `failure` describes the required ordering for the load operation that takes place when
1909 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1910 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1911 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1912 ///
1913 /// **Note:** This method is only available on platforms that support atomic
1914 /// operations on pointers.
1915 ///
1916 /// # Examples
1917 ///
1918 /// ```
1919 /// use std::sync::atomic::{AtomicPtr, Ordering};
1920 ///
1921 /// let some_ptr = AtomicPtr::new(&mut 5);
1922 ///
1923 /// let new = &mut 10;
1924 /// let mut old = some_ptr.load(Ordering::Relaxed);
1925 /// loop {
1926 /// match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
1927 /// Ok(_) => break,
1928 /// Err(x) => old = x,
1929 /// }
1930 /// }
1931 /// ```
1932 ///
1933 /// # Considerations
1934 ///
1935 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1936 /// of CAS operations. In particular, a load of the value followed by a successful
1937 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1938 /// changed the value in the interim. This is usually important when the *equality* check in
1939 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1940 /// does not necessarily imply identity. This is a particularly common case for pointers, as
1941 /// a pointer holding the same address does not imply that the same object exists at that
1942 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
1943 ///
1944 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1945 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1946 #[inline]
1947 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1948 #[cfg(target_has_atomic = "ptr")]
1949 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1950 pub fn compare_exchange_weak(
1951 &self,
1952 current: *mut T,
1953 new: *mut T,
1954 success: Ordering,
1955 failure: Ordering,
1956 ) -> Result<*mut T, *mut T> {
1957 // SAFETY: This intrinsic is unsafe because it operates on a raw pointer
1958 // but we know for sure that the pointer is valid (we just got it from
1959 // an `UnsafeCell` that we have by reference) and the atomic operation
1960 // itself allows us to safely mutate the `UnsafeCell` contents.
1961 unsafe { atomic_compare_exchange_weak(self.p.get(), current, new, success, failure) }
1962 }
1963
1964 /// Fetches the value, and applies a function to it that returns an optional
1965 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1966 /// returned `Some(_)`, else `Err(previous_value)`.
1967 ///
1968 /// Note: This may call the function multiple times if the value has been
1969 /// changed from other threads in the meantime, as long as the function
1970 /// returns `Some(_)`, but the function will have been applied only once to
1971 /// the stored value.
1972 ///
1973 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
1974 /// ordering of this operation. The first describes the required ordering for
1975 /// when the operation finally succeeds while the second describes the
1976 /// required ordering for loads. These correspond to the success and failure
1977 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
1978 ///
1979 /// Using [`Acquire`] as success ordering makes the store part of this
1980 /// operation [`Relaxed`], and using [`Release`] makes the final successful
1981 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1982 /// [`Acquire`] or [`Relaxed`].
1983 ///
1984 /// **Note:** This method is only available on platforms that support atomic
1985 /// operations on pointers.
1986 ///
1987 /// # Considerations
1988 ///
1989 /// This method is not magic; it is not provided by the hardware, and does not act like a
1990 /// critical section or mutex.
1991 ///
1992 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1993 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
1994 /// which is a particularly common pitfall for pointers!
1995 ///
1996 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1997 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1998 ///
1999 /// # Examples
2000 ///
2001 /// ```rust
2002 /// use std::sync::atomic::{AtomicPtr, Ordering};
2003 ///
2004 /// let ptr: *mut _ = &mut 5;
2005 /// let some_ptr = AtomicPtr::new(ptr);
2006 ///
2007 /// let new: *mut _ = &mut 10;
2008 /// assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
2009 /// let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
2010 /// if x == ptr {
2011 /// Some(new)
2012 /// } else {
2013 /// None
2014 /// }
2015 /// });
2016 /// assert_eq!(result, Ok(ptr));
2017 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2018 /// ```
2019 #[inline]
2020 #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
2021 #[cfg(target_has_atomic = "ptr")]
2022 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2023 pub fn fetch_update<F>(
2024 &self,
2025 set_order: Ordering,
2026 fetch_order: Ordering,
2027 mut f: F,
2028 ) -> Result<*mut T, *mut T>
2029 where
2030 F: FnMut(*mut T) -> Option<*mut T>,
2031 {
2032 let mut prev = self.load(fetch_order);
2033 while let Some(next) = f(prev) {
2034 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
2035 x @ Ok(_) => return x,
2036 Err(next_prev) => prev = next_prev,
2037 }
2038 }
2039 Err(prev)
2040 }
2041 /// Fetches the value, and applies a function to it that returns an optional
2042 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
2043 /// returned `Some(_)`, else `Err(previous_value)`.
2044 ///
2045 /// See also: [`update`](`AtomicPtr::update`).
2046 ///
2047 /// Note: This may call the function multiple times if the value has been
2048 /// changed from other threads in the meantime, as long as the function
2049 /// returns `Some(_)`, but the function will have been applied only once to
2050 /// the stored value.
2051 ///
2052 /// `try_update` takes two [`Ordering`] arguments to describe the memory
2053 /// ordering of this operation. The first describes the required ordering for
2054 /// when the operation finally succeeds while the second describes the
2055 /// required ordering for loads. These correspond to the success and failure
2056 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2057 ///
2058 /// Using [`Acquire`] as success ordering makes the store part of this
2059 /// operation [`Relaxed`], and using [`Release`] makes the final successful
2060 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
2061 /// [`Acquire`] or [`Relaxed`].
2062 ///
2063 /// **Note:** This method is only available on platforms that support atomic
2064 /// operations on pointers.
2065 ///
2066 /// # Considerations
2067 ///
2068 /// This method is not magic; it is not provided by the hardware, and does not act like a
2069 /// critical section or mutex.
2070 ///
2071 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2072 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2073 /// which is a particularly common pitfall for pointers!
2074 ///
2075 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2076 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2077 ///
2078 /// # Examples
2079 ///
2080 /// ```rust
2081 /// #![feature(atomic_try_update)]
2082 /// use std::sync::atomic::{AtomicPtr, Ordering};
2083 ///
2084 /// let ptr: *mut _ = &mut 5;
2085 /// let some_ptr = AtomicPtr::new(ptr);
2086 ///
2087 /// let new: *mut _ = &mut 10;
2088 /// assert_eq!(some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
2089 /// let result = some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
2090 /// if x == ptr {
2091 /// Some(new)
2092 /// } else {
2093 /// None
2094 /// }
2095 /// });
2096 /// assert_eq!(result, Ok(ptr));
2097 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2098 /// ```
2099 #[inline]
2100 #[unstable(feature = "atomic_try_update", issue = "135894")]
2101 #[cfg(target_has_atomic = "ptr")]
2102 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2103 pub fn try_update(
2104 &self,
2105 set_order: Ordering,
2106 fetch_order: Ordering,
2107 f: impl FnMut(*mut T) -> Option<*mut T>,
2108 ) -> Result<*mut T, *mut T> {
2109 // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
2110 // when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
2111 self.fetch_update(set_order, fetch_order, f)
2112 }
2113
2114 /// Fetches the value, applies a function to it that it return a new value.
2115 /// The new value is stored and the old value is returned.
2116 ///
2117 /// See also: [`try_update`](`AtomicPtr::try_update`).
2118 ///
2119 /// Note: This may call the function multiple times if the value has been changed from other threads in
2120 /// the meantime, but the function will have been applied only once to the stored value.
2121 ///
2122 /// `update` takes two [`Ordering`] arguments to describe the memory
2123 /// ordering of this operation. The first describes the required ordering for
2124 /// when the operation finally succeeds while the second describes the
2125 /// required ordering for loads. These correspond to the success and failure
2126 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2127 ///
2128 /// Using [`Acquire`] as success ordering makes the store part
2129 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
2130 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
2131 ///
2132 /// **Note:** This method is only available on platforms that support atomic
2133 /// operations on pointers.
2134 ///
2135 /// # Considerations
2136 ///
2137 /// This method is not magic; it is not provided by the hardware, and does not act like a
2138 /// critical section or mutex.
2139 ///
2140 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2141 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2142 /// which is a particularly common pitfall for pointers!
2143 ///
2144 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2145 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2146 ///
2147 /// # Examples
2148 ///
2149 /// ```rust
2150 /// #![feature(atomic_try_update)]
2151 ///
2152 /// use std::sync::atomic::{AtomicPtr, Ordering};
2153 ///
2154 /// let ptr: *mut _ = &mut 5;
2155 /// let some_ptr = AtomicPtr::new(ptr);
2156 ///
2157 /// let new: *mut _ = &mut 10;
2158 /// let result = some_ptr.update(Ordering::SeqCst, Ordering::SeqCst, |_| new);
2159 /// assert_eq!(result, ptr);
2160 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2161 /// ```
2162 #[inline]
2163 #[unstable(feature = "atomic_try_update", issue = "135894")]
2164 #[cfg(target_has_atomic = "8")]
2165 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2166 pub fn update(
2167 &self,
2168 set_order: Ordering,
2169 fetch_order: Ordering,
2170 mut f: impl FnMut(*mut T) -> *mut T,
2171 ) -> *mut T {
2172 let mut prev = self.load(fetch_order);
2173 loop {
2174 match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
2175 Ok(x) => break x,
2176 Err(next_prev) => prev = next_prev,
2177 }
2178 }
2179 }
2180
2181 /// Offsets the pointer's address by adding `val` (in units of `T`),
2182 /// returning the previous pointer.
2183 ///
2184 /// This is equivalent to using [`wrapping_add`] to atomically perform the
2185 /// equivalent of `ptr = ptr.wrapping_add(val);`.
2186 ///
2187 /// This method operates in units of `T`, which means that it cannot be used
2188 /// to offset the pointer by an amount which is not a multiple of
2189 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2190 /// work with a deliberately misaligned pointer. In such cases, you may use
2191 /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead.
2192 ///
2193 /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the
2194 /// memory ordering of this operation. All ordering modes are possible. Note
2195 /// that using [`Acquire`] makes the store part of this operation
2196 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2197 ///
2198 /// **Note**: This method is only available on platforms that support atomic
2199 /// operations on [`AtomicPtr`].
2200 ///
2201 /// [`wrapping_add`]: pointer::wrapping_add
2202 ///
2203 /// # Examples
2204 ///
2205 /// ```
2206 /// use core::sync::atomic::{AtomicPtr, Ordering};
2207 ///
2208 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2209 /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0);
2210 /// // Note: units of `size_of::<i64>()`.
2211 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8);
2212 /// ```
2213 #[inline]
2214 #[cfg(target_has_atomic = "ptr")]
2215 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2216 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2217 pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T {
2218 self.fetch_byte_add(val.wrapping_mul(size_of::<T>()), order)
2219 }
2220
2221 /// Offsets the pointer's address by subtracting `val` (in units of `T`),
2222 /// returning the previous pointer.
2223 ///
2224 /// This is equivalent to using [`wrapping_sub`] to atomically perform the
2225 /// equivalent of `ptr = ptr.wrapping_sub(val);`.
2226 ///
2227 /// This method operates in units of `T`, which means that it cannot be used
2228 /// to offset the pointer by an amount which is not a multiple of
2229 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2230 /// work with a deliberately misaligned pointer. In such cases, you may use
2231 /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead.
2232 ///
2233 /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory
2234 /// ordering of this operation. All ordering modes are possible. Note that
2235 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2236 /// and using [`Release`] makes the load part [`Relaxed`].
2237 ///
2238 /// **Note**: This method is only available on platforms that support atomic
2239 /// operations on [`AtomicPtr`].
2240 ///
2241 /// [`wrapping_sub`]: pointer::wrapping_sub
2242 ///
2243 /// # Examples
2244 ///
2245 /// ```
2246 /// use core::sync::atomic::{AtomicPtr, Ordering};
2247 ///
2248 /// let array = [1i32, 2i32];
2249 /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _);
2250 ///
2251 /// assert!(core::ptr::eq(
2252 /// atom.fetch_ptr_sub(1, Ordering::Relaxed),
2253 /// &array[1],
2254 /// ));
2255 /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0]));
2256 /// ```
2257 #[inline]
2258 #[cfg(target_has_atomic = "ptr")]
2259 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2260 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2261 pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T {
2262 self.fetch_byte_sub(val.wrapping_mul(size_of::<T>()), order)
2263 }
2264
2265 /// Offsets the pointer's address by adding `val` *bytes*, returning the
2266 /// previous pointer.
2267 ///
2268 /// This is equivalent to using [`wrapping_byte_add`] to atomically
2269 /// perform `ptr = ptr.wrapping_byte_add(val)`.
2270 ///
2271 /// `fetch_byte_add` takes an [`Ordering`] argument which describes the
2272 /// memory ordering of this operation. All ordering modes are possible. Note
2273 /// that using [`Acquire`] makes the store part of this operation
2274 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2275 ///
2276 /// **Note**: This method is only available on platforms that support atomic
2277 /// operations on [`AtomicPtr`].
2278 ///
2279 /// [`wrapping_byte_add`]: pointer::wrapping_byte_add
2280 ///
2281 /// # Examples
2282 ///
2283 /// ```
2284 /// use core::sync::atomic::{AtomicPtr, Ordering};
2285 ///
2286 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2287 /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0);
2288 /// // Note: in units of bytes, not `size_of::<i64>()`.
2289 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1);
2290 /// ```
2291 #[inline]
2292 #[cfg(target_has_atomic = "ptr")]
2293 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2294 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2295 pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T {
2296 // SAFETY: data races are prevented by atomic intrinsics.
2297 unsafe { atomic_add(self.p.get(), val, order).cast() }
2298 }
2299
2300 /// Offsets the pointer's address by subtracting `val` *bytes*, returning the
2301 /// previous pointer.
2302 ///
2303 /// This is equivalent to using [`wrapping_byte_sub`] to atomically
2304 /// perform `ptr = ptr.wrapping_byte_sub(val)`.
2305 ///
2306 /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the
2307 /// memory ordering of this operation. All ordering modes are possible. Note
2308 /// that using [`Acquire`] makes the store part of this operation
2309 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2310 ///
2311 /// **Note**: This method is only available on platforms that support atomic
2312 /// operations on [`AtomicPtr`].
2313 ///
2314 /// [`wrapping_byte_sub`]: pointer::wrapping_byte_sub
2315 ///
2316 /// # Examples
2317 ///
2318 /// ```
2319 /// use core::sync::atomic::{AtomicPtr, Ordering};
2320 ///
2321 /// let mut arr = [0i64, 1];
2322 /// let atom = AtomicPtr::<i64>::new(&raw mut arr[1]);
2323 /// assert_eq!(atom.fetch_byte_sub(8, Ordering::Relaxed).addr(), (&raw const arr[1]).addr());
2324 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), (&raw const arr[0]).addr());
2325 /// ```
2326 #[inline]
2327 #[cfg(target_has_atomic = "ptr")]
2328 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2329 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2330 pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T {
2331 // SAFETY: data races are prevented by atomic intrinsics.
2332 unsafe { atomic_sub(self.p.get(), val, order).cast() }
2333 }
2334
2335 /// Performs a bitwise "or" operation on the address of the current pointer,
2336 /// and the argument `val`, and stores a pointer with provenance of the
2337 /// current pointer and the resulting address.
2338 ///
2339 /// This is equivalent to using [`map_addr`] to atomically perform
2340 /// `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged
2341 /// pointer schemes to atomically set tag bits.
2342 ///
2343 /// **Caveat**: This operation returns the previous value. To compute the
2344 /// stored value without losing provenance, you may use [`map_addr`]. For
2345 /// example: `a.fetch_or(val).map_addr(|a| a | val)`.
2346 ///
2347 /// `fetch_or` takes an [`Ordering`] argument which describes the memory
2348 /// ordering of this operation. All ordering modes are possible. Note that
2349 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2350 /// and using [`Release`] makes the load part [`Relaxed`].
2351 ///
2352 /// **Note**: This method is only available on platforms that support atomic
2353 /// operations on [`AtomicPtr`].
2354 ///
2355 /// This API and its claimed semantics are part of the Strict Provenance
2356 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2357 /// details.
2358 ///
2359 /// [`map_addr`]: pointer::map_addr
2360 ///
2361 /// # Examples
2362 ///
2363 /// ```
2364 /// use core::sync::atomic::{AtomicPtr, Ordering};
2365 ///
2366 /// let pointer = &mut 3i64 as *mut i64;
2367 ///
2368 /// let atom = AtomicPtr::<i64>::new(pointer);
2369 /// // Tag the bottom bit of the pointer.
2370 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0);
2371 /// // Extract and untag.
2372 /// let tagged = atom.load(Ordering::Relaxed);
2373 /// assert_eq!(tagged.addr() & 1, 1);
2374 /// assert_eq!(tagged.map_addr(|p| p & !1), pointer);
2375 /// ```
2376 #[inline]
2377 #[cfg(target_has_atomic = "ptr")]
2378 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2379 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2380 pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T {
2381 // SAFETY: data races are prevented by atomic intrinsics.
2382 unsafe { atomic_or(self.p.get(), val, order).cast() }
2383 }
2384
2385 /// Performs a bitwise "and" operation on the address of the current
2386 /// pointer, and the argument `val`, and stores a pointer with provenance of
2387 /// the current pointer and the resulting address.
2388 ///
2389 /// This is equivalent to using [`map_addr`] to atomically perform
2390 /// `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged
2391 /// pointer schemes to atomically unset tag bits.
2392 ///
2393 /// **Caveat**: This operation returns the previous value. To compute the
2394 /// stored value without losing provenance, you may use [`map_addr`]. For
2395 /// example: `a.fetch_and(val).map_addr(|a| a & val)`.
2396 ///
2397 /// `fetch_and` takes an [`Ordering`] argument which describes the memory
2398 /// ordering of this operation. All ordering modes are possible. Note that
2399 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2400 /// and using [`Release`] makes the load part [`Relaxed`].
2401 ///
2402 /// **Note**: This method is only available on platforms that support atomic
2403 /// operations on [`AtomicPtr`].
2404 ///
2405 /// This API and its claimed semantics are part of the Strict Provenance
2406 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2407 /// details.
2408 ///
2409 /// [`map_addr`]: pointer::map_addr
2410 ///
2411 /// # Examples
2412 ///
2413 /// ```
2414 /// use core::sync::atomic::{AtomicPtr, Ordering};
2415 ///
2416 /// let pointer = &mut 3i64 as *mut i64;
2417 /// // A tagged pointer
2418 /// let atom = AtomicPtr::<i64>::new(pointer.map_addr(|a| a | 1));
2419 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1);
2420 /// // Untag, and extract the previously tagged pointer.
2421 /// let untagged = atom.fetch_and(!1, Ordering::Relaxed)
2422 /// .map_addr(|a| a & !1);
2423 /// assert_eq!(untagged, pointer);
2424 /// ```
2425 #[inline]
2426 #[cfg(target_has_atomic = "ptr")]
2427 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2428 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2429 pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T {
2430 // SAFETY: data races are prevented by atomic intrinsics.
2431 unsafe { atomic_and(self.p.get(), val, order).cast() }
2432 }
2433
2434 /// Performs a bitwise "xor" operation on the address of the current
2435 /// pointer, and the argument `val`, and stores a pointer with provenance of
2436 /// the current pointer and the resulting address.
2437 ///
2438 /// This is equivalent to using [`map_addr`] to atomically perform
2439 /// `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged
2440 /// pointer schemes to atomically toggle tag bits.
2441 ///
2442 /// **Caveat**: This operation returns the previous value. To compute the
2443 /// stored value without losing provenance, you may use [`map_addr`]. For
2444 /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`.
2445 ///
2446 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory
2447 /// ordering of this operation. All ordering modes are possible. Note that
2448 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2449 /// and using [`Release`] makes the load part [`Relaxed`].
2450 ///
2451 /// **Note**: This method is only available on platforms that support atomic
2452 /// operations on [`AtomicPtr`].
2453 ///
2454 /// This API and its claimed semantics are part of the Strict Provenance
2455 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2456 /// details.
2457 ///
2458 /// [`map_addr`]: pointer::map_addr
2459 ///
2460 /// # Examples
2461 ///
2462 /// ```
2463 /// use core::sync::atomic::{AtomicPtr, Ordering};
2464 ///
2465 /// let pointer = &mut 3i64 as *mut i64;
2466 /// let atom = AtomicPtr::<i64>::new(pointer);
2467 ///
2468 /// // Toggle a tag bit on the pointer.
2469 /// atom.fetch_xor(1, Ordering::Relaxed);
2470 /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1);
2471 /// ```
2472 #[inline]
2473 #[cfg(target_has_atomic = "ptr")]
2474 #[stable(feature = "strict_provenance_atomic_ptr", since = "1.91.0")]
2475 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2476 pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T {
2477 // SAFETY: data races are prevented by atomic intrinsics.
2478 unsafe { atomic_xor(self.p.get(), val, order).cast() }
2479 }
2480
2481 /// Returns a mutable pointer to the underlying pointer.
2482 ///
2483 /// Doing non-atomic reads and writes on the resulting pointer can be a data race.
2484 /// This method is mostly useful for FFI, where the function signature may use
2485 /// `*mut *mut T` instead of `&AtomicPtr<T>`.
2486 ///
2487 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
2488 /// atomic types work with interior mutability. All modifications of an atomic change the value
2489 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
2490 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
2491 /// requirements of the [memory model].
2492 ///
2493 /// # Examples
2494 ///
2495 /// ```ignore (extern-declaration)
2496 /// use std::sync::atomic::AtomicPtr;
2497 ///
2498 /// extern "C" {
2499 /// fn my_atomic_op(arg: *mut *mut u32);
2500 /// }
2501 ///
2502 /// let mut value = 17;
2503 /// let atomic = AtomicPtr::new(&mut value);
2504 ///
2505 /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
2506 /// unsafe {
2507 /// my_atomic_op(atomic.as_ptr());
2508 /// }
2509 /// ```
2510 ///
2511 /// [memory model]: self#memory-model-for-atomic-accesses
2512 #[inline]
2513 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
2514 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
2515 #[rustc_never_returns_null_ptr]
2516 pub const fn as_ptr(&self) -> *mut *mut T {
2517 self.p.get()
2518 }
2519}
2520
2521#[cfg(target_has_atomic_load_store = "8")]
2522#[stable(feature = "atomic_bool_from", since = "1.24.0")]
2523#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2524impl const From<bool> for AtomicBool {
2525 /// Converts a `bool` into an `AtomicBool`.
2526 ///
2527 /// # Examples
2528 ///
2529 /// ```
2530 /// use std::sync::atomic::AtomicBool;
2531 /// let atomic_bool = AtomicBool::from(true);
2532 /// assert_eq!(format!("{atomic_bool:?}"), "true")
2533 /// ```
2534 #[inline]
2535 fn from(b: bool) -> Self {
2536 Self::new(b)
2537 }
2538}
2539
2540#[cfg(target_has_atomic_load_store = "ptr")]
2541#[stable(feature = "atomic_from", since = "1.23.0")]
2542#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2543impl<T> const From<*mut T> for AtomicPtr<T> {
2544 /// Converts a `*mut T` into an `AtomicPtr<T>`.
2545 #[inline]
2546 fn from(p: *mut T) -> Self {
2547 Self::new(p)
2548 }
2549}
2550
2551#[allow(unused_macros)] // This macro ends up being unused on some architectures.
2552macro_rules! if_8_bit {
2553 (u8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2554 (i8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2555 ($_:ident, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($no)*)?) };
2556}
2557
2558#[cfg(target_has_atomic_load_store)]
2559macro_rules! atomic_int {
2560 ($cfg_cas:meta,
2561 $cfg_align:meta,
2562 $stable:meta,
2563 $stable_cxchg:meta,
2564 $stable_debug:meta,
2565 $stable_access:meta,
2566 $stable_from:meta,
2567 $stable_nand:meta,
2568 $const_stable_new:meta,
2569 $const_stable_into_inner:meta,
2570 $diagnostic_item:meta,
2571 $s_int_type:literal,
2572 $extra_feature:expr,
2573 $min_fn:ident, $max_fn:ident,
2574 $align:expr,
2575 $int_type:ident $atomic_type:ident) => {
2576 /// An integer type which can be safely shared between threads.
2577 ///
2578 /// This type has the same
2579 #[doc = if_8_bit!(
2580 $int_type,
2581 yes = ["size, alignment, and bit validity"],
2582 no = ["size and bit validity"],
2583 )]
2584 /// as the underlying integer type, [`
2585 #[doc = $s_int_type]
2586 /// `].
2587 #[doc = if_8_bit! {
2588 $int_type,
2589 no = [
2590 "However, the alignment of this type is always equal to its ",
2591 "size, even on targets where [`", $s_int_type, "`] has a ",
2592 "lesser alignment."
2593 ],
2594 }]
2595 ///
2596 /// For more about the differences between atomic types and
2597 /// non-atomic types as well as information about the portability of
2598 /// this type, please see the [module-level documentation].
2599 ///
2600 /// **Note:** This type is only available on platforms that support
2601 /// atomic loads and stores of [`
2602 #[doc = $s_int_type]
2603 /// `].
2604 ///
2605 /// [module-level documentation]: crate::sync::atomic
2606 #[$stable]
2607 #[$diagnostic_item]
2608 #[repr(C, align($align))]
2609 pub struct $atomic_type {
2610 v: UnsafeCell<$int_type>,
2611 }
2612
2613 #[$stable]
2614 impl Default for $atomic_type {
2615 #[inline]
2616 fn default() -> Self {
2617 Self::new(Default::default())
2618 }
2619 }
2620
2621 #[$stable_from]
2622 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2623 impl const From<$int_type> for $atomic_type {
2624 #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")]
2625 #[inline]
2626 fn from(v: $int_type) -> Self { Self::new(v) }
2627 }
2628
2629 #[$stable_debug]
2630 impl fmt::Debug for $atomic_type {
2631 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2632 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
2633 }
2634 }
2635
2636 // Send is implicitly implemented.
2637 #[$stable]
2638 unsafe impl Sync for $atomic_type {}
2639
2640 impl $atomic_type {
2641 /// Creates a new atomic integer.
2642 ///
2643 /// # Examples
2644 ///
2645 /// ```
2646 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2647 ///
2648 #[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")]
2649 /// ```
2650 #[inline]
2651 #[$stable]
2652 #[$const_stable_new]
2653 #[must_use]
2654 pub const fn new(v: $int_type) -> Self {
2655 Self {v: UnsafeCell::new(v)}
2656 }
2657
2658 /// Creates a new reference to an atomic integer from a pointer.
2659 ///
2660 /// # Examples
2661 ///
2662 /// ```
2663 #[doc = concat!($extra_feature, "use std::sync::atomic::{self, ", stringify!($atomic_type), "};")]
2664 ///
2665 /// // Get a pointer to an allocated value
2666 #[doc = concat!("let ptr: *mut ", stringify!($int_type), " = Box::into_raw(Box::new(0));")]
2667 ///
2668 #[doc = concat!("assert!(ptr.cast::<", stringify!($atomic_type), ">().is_aligned());")]
2669 ///
2670 /// {
2671 /// // Create an atomic view of the allocated value
2672 // SAFETY: this is a doc comment, tidy, it can't hurt you (also guaranteed by the construction of `ptr` and the assert above)
2673 #[doc = concat!(" let atomic = unsafe {", stringify!($atomic_type), "::from_ptr(ptr) };")]
2674 ///
2675 /// // Use `atomic` for atomic operations, possibly share it with other threads
2676 /// atomic.store(1, atomic::Ordering::Relaxed);
2677 /// }
2678 ///
2679 /// // It's ok to non-atomically access the value behind `ptr`,
2680 /// // since the reference to the atomic ended its lifetime in the block above
2681 /// assert_eq!(unsafe { *ptr }, 1);
2682 ///
2683 /// // Deallocate the value
2684 /// unsafe { drop(Box::from_raw(ptr)) }
2685 /// ```
2686 ///
2687 /// # Safety
2688 ///
2689 /// * `ptr` must be aligned to
2690 #[doc = concat!(" `align_of::<", stringify!($atomic_type), ">()`")]
2691 #[doc = if_8_bit!{
2692 $int_type,
2693 yes = [
2694 " (note that this is always true, since `align_of::<",
2695 stringify!($atomic_type), ">() == 1`)."
2696 ],
2697 no = [
2698 " (note that on some platforms this can be bigger than `align_of::<",
2699 stringify!($int_type), ">()`)."
2700 ],
2701 }]
2702 /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
2703 /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
2704 /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
2705 /// sizes, without synchronization.
2706 ///
2707 /// [valid]: crate::ptr#safety
2708 /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
2709 #[inline]
2710 #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
2711 #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
2712 pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type {
2713 // SAFETY: guaranteed by the caller
2714 unsafe { &*ptr.cast() }
2715 }
2716
2717
2718 /// Returns a mutable reference to the underlying integer.
2719 ///
2720 /// This is safe because the mutable reference guarantees that no other threads are
2721 /// concurrently accessing the atomic data.
2722 ///
2723 /// # Examples
2724 ///
2725 /// ```
2726 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2727 ///
2728 #[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")]
2729 /// assert_eq!(*some_var.get_mut(), 10);
2730 /// *some_var.get_mut() = 5;
2731 /// assert_eq!(some_var.load(Ordering::SeqCst), 5);
2732 /// ```
2733 #[inline]
2734 #[$stable_access]
2735 pub fn get_mut(&mut self) -> &mut $int_type {
2736 self.v.get_mut()
2737 }
2738
2739 #[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")]
2740 ///
2741 #[doc = if_8_bit! {
2742 $int_type,
2743 no = [
2744 "**Note:** This function is only available on targets where `",
2745 stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
2746 ],
2747 }]
2748 ///
2749 /// # Examples
2750 ///
2751 /// ```
2752 /// #![feature(atomic_from_mut)]
2753 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2754 ///
2755 /// let mut some_int = 123;
2756 #[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")]
2757 /// a.store(100, Ordering::Relaxed);
2758 /// assert_eq!(some_int, 100);
2759 /// ```
2760 ///
2761 #[inline]
2762 #[$cfg_align]
2763 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2764 pub fn from_mut(v: &mut $int_type) -> &mut Self {
2765 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2766 // SAFETY:
2767 // - the mutable reference guarantees unique ownership.
2768 // - the alignment of `$int_type` and `Self` is the
2769 // same, as promised by $cfg_align and verified above.
2770 unsafe { &mut *(v as *mut $int_type as *mut Self) }
2771 }
2772
2773 #[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")]
2774 ///
2775 /// This is safe because the mutable reference guarantees that no other threads are
2776 /// concurrently accessing the atomic data.
2777 ///
2778 /// # Examples
2779 ///
2780 /// ```ignore-wasm
2781 /// #![feature(atomic_from_mut)]
2782 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2783 ///
2784 #[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")]
2785 ///
2786 #[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")]
2787 /// assert_eq!(view, [0; 10]);
2788 /// view
2789 /// .iter_mut()
2790 /// .enumerate()
2791 /// .for_each(|(idx, int)| *int = idx as _);
2792 ///
2793 /// std::thread::scope(|s| {
2794 /// some_ints
2795 /// .iter()
2796 /// .enumerate()
2797 /// .for_each(|(idx, int)| {
2798 /// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
2799 /// })
2800 /// });
2801 /// ```
2802 #[inline]
2803 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2804 pub fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] {
2805 // SAFETY: the mutable reference guarantees unique ownership.
2806 unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) }
2807 }
2808
2809 #[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")]
2810 ///
2811 #[doc = if_8_bit! {
2812 $int_type,
2813 no = [
2814 "**Note:** This function is only available on targets where `",
2815 stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
2816 ],
2817 }]
2818 ///
2819 /// # Examples
2820 ///
2821 /// ```ignore-wasm
2822 /// #![feature(atomic_from_mut)]
2823 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2824 ///
2825 /// let mut some_ints = [0; 10];
2826 #[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")]
2827 /// std::thread::scope(|s| {
2828 /// for i in 0..a.len() {
2829 /// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
2830 /// }
2831 /// });
2832 /// for (i, n) in some_ints.into_iter().enumerate() {
2833 /// assert_eq!(i, n as usize);
2834 /// }
2835 /// ```
2836 #[inline]
2837 #[$cfg_align]
2838 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2839 pub fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] {
2840 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2841 // SAFETY:
2842 // - the mutable reference guarantees unique ownership.
2843 // - the alignment of `$int_type` and `Self` is the
2844 // same, as promised by $cfg_align and verified above.
2845 unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) }
2846 }
2847
2848 /// Consumes the atomic and returns the contained value.
2849 ///
2850 /// This is safe because passing `self` by value guarantees that no other threads are
2851 /// concurrently accessing the atomic data.
2852 ///
2853 /// # Examples
2854 ///
2855 /// ```
2856 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2857 ///
2858 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2859 /// assert_eq!(some_var.into_inner(), 5);
2860 /// ```
2861 #[inline]
2862 #[$stable_access]
2863 #[$const_stable_into_inner]
2864 pub const fn into_inner(self) -> $int_type {
2865 self.v.into_inner()
2866 }
2867
2868 /// Loads a value from the atomic integer.
2869 ///
2870 /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2871 /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
2872 ///
2873 /// # Panics
2874 ///
2875 /// Panics if `order` is [`Release`] or [`AcqRel`].
2876 ///
2877 /// # Examples
2878 ///
2879 /// ```
2880 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2881 ///
2882 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2883 ///
2884 /// assert_eq!(some_var.load(Ordering::Relaxed), 5);
2885 /// ```
2886 #[inline]
2887 #[$stable]
2888 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2889 pub fn load(&self, order: Ordering) -> $int_type {
2890 // SAFETY: data races are prevented by atomic intrinsics.
2891 unsafe { atomic_load(self.v.get(), order) }
2892 }
2893
2894 /// Stores a value into the atomic integer.
2895 ///
2896 /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2897 /// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
2898 ///
2899 /// # Panics
2900 ///
2901 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
2902 ///
2903 /// # Examples
2904 ///
2905 /// ```
2906 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2907 ///
2908 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2909 ///
2910 /// some_var.store(10, Ordering::Relaxed);
2911 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2912 /// ```
2913 #[inline]
2914 #[$stable]
2915 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2916 pub fn store(&self, val: $int_type, order: Ordering) {
2917 // SAFETY: data races are prevented by atomic intrinsics.
2918 unsafe { atomic_store(self.v.get(), val, order); }
2919 }
2920
2921 /// Stores a value into the atomic integer, returning the previous value.
2922 ///
2923 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
2924 /// of this operation. All ordering modes are possible. Note that using
2925 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2926 /// using [`Release`] makes the load part [`Relaxed`].
2927 ///
2928 /// **Note**: This method is only available on platforms that support atomic operations on
2929 #[doc = concat!("[`", $s_int_type, "`].")]
2930 ///
2931 /// # Examples
2932 ///
2933 /// ```
2934 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2935 ///
2936 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2937 ///
2938 /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
2939 /// ```
2940 #[inline]
2941 #[$stable]
2942 #[$cfg_cas]
2943 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2944 pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
2945 // SAFETY: data races are prevented by atomic intrinsics.
2946 unsafe { atomic_swap(self.v.get(), val, order) }
2947 }
2948
2949 /// Stores a value into the atomic integer if the current value is the same as
2950 /// the `current` value.
2951 ///
2952 /// The return value is always the previous value. If it is equal to `current`, then the
2953 /// value was updated.
2954 ///
2955 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
2956 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
2957 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
2958 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
2959 /// happens, and using [`Release`] makes the load part [`Relaxed`].
2960 ///
2961 /// **Note**: This method is only available on platforms that support atomic operations on
2962 #[doc = concat!("[`", $s_int_type, "`].")]
2963 ///
2964 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
2965 ///
2966 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
2967 /// memory orderings:
2968 ///
2969 /// Original | Success | Failure
2970 /// -------- | ------- | -------
2971 /// Relaxed | Relaxed | Relaxed
2972 /// Acquire | Acquire | Acquire
2973 /// Release | Release | Relaxed
2974 /// AcqRel | AcqRel | Acquire
2975 /// SeqCst | SeqCst | SeqCst
2976 ///
2977 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
2978 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
2979 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
2980 /// rather than to infer success vs failure based on the value that was read.
2981 ///
2982 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
2983 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
2984 /// which allows the compiler to generate better assembly code when the compare and swap
2985 /// is used in a loop.
2986 ///
2987 /// # Examples
2988 ///
2989 /// ```
2990 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2991 ///
2992 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2993 ///
2994 /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
2995 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2996 ///
2997 /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
2998 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2999 /// ```
3000 #[inline]
3001 #[$stable]
3002 #[deprecated(
3003 since = "1.50.0",
3004 note = "Use `compare_exchange` or `compare_exchange_weak` instead")
3005 ]
3006 #[$cfg_cas]
3007 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3008 pub fn compare_and_swap(&self,
3009 current: $int_type,
3010 new: $int_type,
3011 order: Ordering) -> $int_type {
3012 match self.compare_exchange(current,
3013 new,
3014 order,
3015 strongest_failure_ordering(order)) {
3016 Ok(x) => x,
3017 Err(x) => x,
3018 }
3019 }
3020
3021 /// Stores a value into the atomic integer if the current value is the same as
3022 /// the `current` value.
3023 ///
3024 /// The return value is a result indicating whether the new value was written and
3025 /// containing the previous value. On success this value is guaranteed to be equal to
3026 /// `current`.
3027 ///
3028 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
3029 /// ordering of this operation. `success` describes the required ordering for the
3030 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3031 /// `failure` describes the required ordering for the load operation that takes place when
3032 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3033 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3034 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3035 ///
3036 /// **Note**: This method is only available on platforms that support atomic operations on
3037 #[doc = concat!("[`", $s_int_type, "`].")]
3038 ///
3039 /// # Examples
3040 ///
3041 /// ```
3042 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3043 ///
3044 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
3045 ///
3046 /// assert_eq!(some_var.compare_exchange(5, 10,
3047 /// Ordering::Acquire,
3048 /// Ordering::Relaxed),
3049 /// Ok(5));
3050 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3051 ///
3052 /// assert_eq!(some_var.compare_exchange(6, 12,
3053 /// Ordering::SeqCst,
3054 /// Ordering::Acquire),
3055 /// Err(10));
3056 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3057 /// ```
3058 ///
3059 /// # Considerations
3060 ///
3061 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3062 /// of CAS operations. In particular, a load of the value followed by a successful
3063 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3064 /// changed the value in the interim! This is usually important when the *equality* check in
3065 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3066 /// does not necessarily imply identity. This is a particularly common case for pointers, as
3067 /// a pointer holding the same address does not imply that the same object exists at that
3068 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3069 ///
3070 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3071 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3072 #[inline]
3073 #[$stable_cxchg]
3074 #[$cfg_cas]
3075 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3076 pub fn compare_exchange(&self,
3077 current: $int_type,
3078 new: $int_type,
3079 success: Ordering,
3080 failure: Ordering) -> Result<$int_type, $int_type> {
3081 // SAFETY: data races are prevented by atomic intrinsics.
3082 unsafe { atomic_compare_exchange(self.v.get(), current, new, success, failure) }
3083 }
3084
3085 /// Stores a value into the atomic integer if the current value is the same as
3086 /// the `current` value.
3087 ///
3088 #[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")]
3089 /// this function is allowed to spuriously fail even
3090 /// when the comparison succeeds, which can result in more efficient code on some
3091 /// platforms. The return value is a result indicating whether the new value was
3092 /// written and containing the previous value.
3093 ///
3094 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
3095 /// ordering of this operation. `success` describes the required ordering for the
3096 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3097 /// `failure` describes the required ordering for the load operation that takes place when
3098 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3099 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3100 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3101 ///
3102 /// **Note**: This method is only available on platforms that support atomic operations on
3103 #[doc = concat!("[`", $s_int_type, "`].")]
3104 ///
3105 /// # Examples
3106 ///
3107 /// ```
3108 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3109 ///
3110 #[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")]
3111 ///
3112 /// let mut old = val.load(Ordering::Relaxed);
3113 /// loop {
3114 /// let new = old * 2;
3115 /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
3116 /// Ok(_) => break,
3117 /// Err(x) => old = x,
3118 /// }
3119 /// }
3120 /// ```
3121 ///
3122 /// # Considerations
3123 ///
3124 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3125 /// of CAS operations. In particular, a load of the value followed by a successful
3126 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3127 /// changed the value in the interim. This is usually important when the *equality* check in
3128 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3129 /// does not necessarily imply identity. This is a particularly common case for pointers, as
3130 /// a pointer holding the same address does not imply that the same object exists at that
3131 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3132 ///
3133 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3134 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3135 #[inline]
3136 #[$stable_cxchg]
3137 #[$cfg_cas]
3138 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3139 pub fn compare_exchange_weak(&self,
3140 current: $int_type,
3141 new: $int_type,
3142 success: Ordering,
3143 failure: Ordering) -> Result<$int_type, $int_type> {
3144 // SAFETY: data races are prevented by atomic intrinsics.
3145 unsafe {
3146 atomic_compare_exchange_weak(self.v.get(), current, new, success, failure)
3147 }
3148 }
3149
3150 /// Adds to the current value, returning the previous value.
3151 ///
3152 /// This operation wraps around on overflow.
3153 ///
3154 /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
3155 /// of this operation. All ordering modes are possible. Note that using
3156 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3157 /// using [`Release`] makes the load part [`Relaxed`].
3158 ///
3159 /// **Note**: This method is only available on platforms that support atomic operations on
3160 #[doc = concat!("[`", $s_int_type, "`].")]
3161 ///
3162 /// # Examples
3163 ///
3164 /// ```
3165 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3166 ///
3167 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")]
3168 /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
3169 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3170 /// ```
3171 #[inline]
3172 #[$stable]
3173 #[$cfg_cas]
3174 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3175 pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
3176 // SAFETY: data races are prevented by atomic intrinsics.
3177 unsafe { atomic_add(self.v.get(), val, order) }
3178 }
3179
3180 /// Subtracts from the current value, returning the previous value.
3181 ///
3182 /// This operation wraps around on overflow.
3183 ///
3184 /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
3185 /// of this operation. All ordering modes are possible. Note that using
3186 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3187 /// using [`Release`] makes the load part [`Relaxed`].
3188 ///
3189 /// **Note**: This method is only available on platforms that support atomic operations on
3190 #[doc = concat!("[`", $s_int_type, "`].")]
3191 ///
3192 /// # Examples
3193 ///
3194 /// ```
3195 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3196 ///
3197 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")]
3198 /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
3199 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3200 /// ```
3201 #[inline]
3202 #[$stable]
3203 #[$cfg_cas]
3204 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3205 pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
3206 // SAFETY: data races are prevented by atomic intrinsics.
3207 unsafe { atomic_sub(self.v.get(), val, order) }
3208 }
3209
3210 /// Bitwise "and" with the current value.
3211 ///
3212 /// Performs a bitwise "and" operation on the current value and the argument `val`, and
3213 /// sets the new value to the result.
3214 ///
3215 /// Returns the previous value.
3216 ///
3217 /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
3218 /// of this operation. All ordering modes are possible. Note that using
3219 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3220 /// using [`Release`] makes the load part [`Relaxed`].
3221 ///
3222 /// **Note**: This method is only available on platforms that support atomic operations on
3223 #[doc = concat!("[`", $s_int_type, "`].")]
3224 ///
3225 /// # Examples
3226 ///
3227 /// ```
3228 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3229 ///
3230 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3231 /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
3232 /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
3233 /// ```
3234 #[inline]
3235 #[$stable]
3236 #[$cfg_cas]
3237 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3238 pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
3239 // SAFETY: data races are prevented by atomic intrinsics.
3240 unsafe { atomic_and(self.v.get(), val, order) }
3241 }
3242
3243 /// Bitwise "nand" with the current value.
3244 ///
3245 /// Performs a bitwise "nand" operation on the current value and the argument `val`, and
3246 /// sets the new value to the result.
3247 ///
3248 /// Returns the previous value.
3249 ///
3250 /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
3251 /// of this operation. All ordering modes are possible. Note that using
3252 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3253 /// using [`Release`] makes the load part [`Relaxed`].
3254 ///
3255 /// **Note**: This method is only available on platforms that support atomic operations on
3256 #[doc = concat!("[`", $s_int_type, "`].")]
3257 ///
3258 /// # Examples
3259 ///
3260 /// ```
3261 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3262 ///
3263 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")]
3264 /// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
3265 /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
3266 /// ```
3267 #[inline]
3268 #[$stable_nand]
3269 #[$cfg_cas]
3270 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3271 pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
3272 // SAFETY: data races are prevented by atomic intrinsics.
3273 unsafe { atomic_nand(self.v.get(), val, order) }
3274 }
3275
3276 /// Bitwise "or" with the current value.
3277 ///
3278 /// Performs a bitwise "or" operation on the current value and the argument `val`, and
3279 /// sets the new value to the result.
3280 ///
3281 /// Returns the previous value.
3282 ///
3283 /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
3284 /// of this operation. All ordering modes are possible. Note that using
3285 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3286 /// using [`Release`] makes the load part [`Relaxed`].
3287 ///
3288 /// **Note**: This method is only available on platforms that support atomic operations on
3289 #[doc = concat!("[`", $s_int_type, "`].")]
3290 ///
3291 /// # Examples
3292 ///
3293 /// ```
3294 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3295 ///
3296 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3297 /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
3298 /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
3299 /// ```
3300 #[inline]
3301 #[$stable]
3302 #[$cfg_cas]
3303 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3304 pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
3305 // SAFETY: data races are prevented by atomic intrinsics.
3306 unsafe { atomic_or(self.v.get(), val, order) }
3307 }
3308
3309 /// Bitwise "xor" with the current value.
3310 ///
3311 /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
3312 /// sets the new value to the result.
3313 ///
3314 /// Returns the previous value.
3315 ///
3316 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
3317 /// of this operation. All ordering modes are possible. Note that using
3318 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3319 /// using [`Release`] makes the load part [`Relaxed`].
3320 ///
3321 /// **Note**: This method is only available on platforms that support atomic operations on
3322 #[doc = concat!("[`", $s_int_type, "`].")]
3323 ///
3324 /// # Examples
3325 ///
3326 /// ```
3327 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3328 ///
3329 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3330 /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
3331 /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
3332 /// ```
3333 #[inline]
3334 #[$stable]
3335 #[$cfg_cas]
3336 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3337 pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
3338 // SAFETY: data races are prevented by atomic intrinsics.
3339 unsafe { atomic_xor(self.v.get(), val, order) }
3340 }
3341
3342 /// Fetches the value, and applies a function to it that returns an optional
3343 /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3344 /// `Err(previous_value)`.
3345 ///
3346 /// Note: This may call the function multiple times if the value has been changed from other threads in
3347 /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3348 /// only once to the stored value.
3349 ///
3350 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3351 /// The first describes the required ordering for when the operation finally succeeds while the second
3352 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3353 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3354 /// respectively.
3355 ///
3356 /// Using [`Acquire`] as success ordering makes the store part
3357 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3358 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3359 ///
3360 /// **Note**: This method is only available on platforms that support atomic operations on
3361 #[doc = concat!("[`", $s_int_type, "`].")]
3362 ///
3363 /// # Considerations
3364 ///
3365 /// This method is not magic; it is not provided by the hardware, and does not act like a
3366 /// critical section or mutex.
3367 ///
3368 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3369 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3370 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3371 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3372 ///
3373 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3374 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3375 ///
3376 /// # Examples
3377 ///
3378 /// ```rust
3379 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3380 ///
3381 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3382 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3383 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3384 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3385 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3386 /// ```
3387 #[inline]
3388 #[stable(feature = "no_more_cas", since = "1.45.0")]
3389 #[$cfg_cas]
3390 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3391 pub fn fetch_update<F>(&self,
3392 set_order: Ordering,
3393 fetch_order: Ordering,
3394 mut f: F) -> Result<$int_type, $int_type>
3395 where F: FnMut($int_type) -> Option<$int_type> {
3396 let mut prev = self.load(fetch_order);
3397 while let Some(next) = f(prev) {
3398 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
3399 x @ Ok(_) => return x,
3400 Err(next_prev) => prev = next_prev
3401 }
3402 }
3403 Err(prev)
3404 }
3405
3406 /// Fetches the value, and applies a function to it that returns an optional
3407 /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3408 /// `Err(previous_value)`.
3409 ///
3410 #[doc = concat!("See also: [`update`](`", stringify!($atomic_type), "::update`).")]
3411 ///
3412 /// Note: This may call the function multiple times if the value has been changed from other threads in
3413 /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3414 /// only once to the stored value.
3415 ///
3416 /// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3417 /// The first describes the required ordering for when the operation finally succeeds while the second
3418 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3419 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3420 /// respectively.
3421 ///
3422 /// Using [`Acquire`] as success ordering makes the store part
3423 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3424 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3425 ///
3426 /// **Note**: This method is only available on platforms that support atomic operations on
3427 #[doc = concat!("[`", $s_int_type, "`].")]
3428 ///
3429 /// # Considerations
3430 ///
3431 /// This method is not magic; it is not provided by the hardware, and does not act like a
3432 /// critical section or mutex.
3433 ///
3434 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3435 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3436 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3437 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3438 ///
3439 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3440 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3441 ///
3442 /// # Examples
3443 ///
3444 /// ```rust
3445 /// #![feature(atomic_try_update)]
3446 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3447 ///
3448 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3449 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3450 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3451 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3452 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3453 /// ```
3454 #[inline]
3455 #[unstable(feature = "atomic_try_update", issue = "135894")]
3456 #[$cfg_cas]
3457 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3458 pub fn try_update(
3459 &self,
3460 set_order: Ordering,
3461 fetch_order: Ordering,
3462 f: impl FnMut($int_type) -> Option<$int_type>,
3463 ) -> Result<$int_type, $int_type> {
3464 // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
3465 // when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
3466 self.fetch_update(set_order, fetch_order, f)
3467 }
3468
3469 /// Fetches the value, applies a function to it that it return a new value.
3470 /// The new value is stored and the old value is returned.
3471 ///
3472 #[doc = concat!("See also: [`try_update`](`", stringify!($atomic_type), "::try_update`).")]
3473 ///
3474 /// Note: This may call the function multiple times if the value has been changed from other threads in
3475 /// the meantime, but the function will have been applied only once to the stored value.
3476 ///
3477 /// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3478 /// The first describes the required ordering for when the operation finally succeeds while the second
3479 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3480 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3481 /// respectively.
3482 ///
3483 /// Using [`Acquire`] as success ordering makes the store part
3484 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3485 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3486 ///
3487 /// **Note**: This method is only available on platforms that support atomic operations on
3488 #[doc = concat!("[`", $s_int_type, "`].")]
3489 ///
3490 /// # Considerations
3491 ///
3492 /// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3493 /// This method is not magic; it is not provided by the hardware, and does not act like a
3494 /// critical section or mutex.
3495 ///
3496 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3497 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3498 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3499 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3500 ///
3501 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3502 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3503 ///
3504 /// # Examples
3505 ///
3506 /// ```rust
3507 /// #![feature(atomic_try_update)]
3508 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3509 ///
3510 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3511 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
3512 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
3513 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3514 /// ```
3515 #[inline]
3516 #[unstable(feature = "atomic_try_update", issue = "135894")]
3517 #[$cfg_cas]
3518 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3519 pub fn update(
3520 &self,
3521 set_order: Ordering,
3522 fetch_order: Ordering,
3523 mut f: impl FnMut($int_type) -> $int_type,
3524 ) -> $int_type {
3525 let mut prev = self.load(fetch_order);
3526 loop {
3527 match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
3528 Ok(x) => break x,
3529 Err(next_prev) => prev = next_prev,
3530 }
3531 }
3532 }
3533
3534 /// Maximum with the current value.
3535 ///
3536 /// Finds the maximum of the current value and the argument `val`, and
3537 /// sets the new value to the result.
3538 ///
3539 /// Returns the previous value.
3540 ///
3541 /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
3542 /// of this operation. All ordering modes are possible. Note that using
3543 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3544 /// using [`Release`] makes the load part [`Relaxed`].
3545 ///
3546 /// **Note**: This method is only available on platforms that support atomic operations on
3547 #[doc = concat!("[`", $s_int_type, "`].")]
3548 ///
3549 /// # Examples
3550 ///
3551 /// ```
3552 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3553 ///
3554 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3555 /// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
3556 /// assert_eq!(foo.load(Ordering::SeqCst), 42);
3557 /// ```
3558 ///
3559 /// If you want to obtain the maximum value in one step, you can use the following:
3560 ///
3561 /// ```
3562 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3563 ///
3564 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3565 /// let bar = 42;
3566 /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
3567 /// assert!(max_foo == 42);
3568 /// ```
3569 #[inline]
3570 #[stable(feature = "atomic_min_max", since = "1.45.0")]
3571 #[$cfg_cas]
3572 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3573 pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
3574 // SAFETY: data races are prevented by atomic intrinsics.
3575 unsafe { $max_fn(self.v.get(), val, order) }
3576 }
3577
3578 /// Minimum with the current value.
3579 ///
3580 /// Finds the minimum of the current value and the argument `val`, and
3581 /// sets the new value to the result.
3582 ///
3583 /// Returns the previous value.
3584 ///
3585 /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
3586 /// of this operation. All ordering modes are possible. Note that using
3587 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3588 /// using [`Release`] makes the load part [`Relaxed`].
3589 ///
3590 /// **Note**: This method is only available on platforms that support atomic operations on
3591 #[doc = concat!("[`", $s_int_type, "`].")]
3592 ///
3593 /// # Examples
3594 ///
3595 /// ```
3596 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3597 ///
3598 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3599 /// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
3600 /// assert_eq!(foo.load(Ordering::Relaxed), 23);
3601 /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
3602 /// assert_eq!(foo.load(Ordering::Relaxed), 22);
3603 /// ```
3604 ///
3605 /// If you want to obtain the minimum value in one step, you can use the following:
3606 ///
3607 /// ```
3608 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3609 ///
3610 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3611 /// let bar = 12;
3612 /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
3613 /// assert_eq!(min_foo, 12);
3614 /// ```
3615 #[inline]
3616 #[stable(feature = "atomic_min_max", since = "1.45.0")]
3617 #[$cfg_cas]
3618 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3619 pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
3620 // SAFETY: data races are prevented by atomic intrinsics.
3621 unsafe { $min_fn(self.v.get(), val, order) }
3622 }
3623
3624 /// Returns a mutable pointer to the underlying integer.
3625 ///
3626 /// Doing non-atomic reads and writes on the resulting integer can be a data race.
3627 /// This method is mostly useful for FFI, where the function signature may use
3628 #[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")]
3629 ///
3630 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
3631 /// atomic types work with interior mutability. All modifications of an atomic change the value
3632 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
3633 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
3634 /// requirements of the [memory model].
3635 ///
3636 /// # Examples
3637 ///
3638 /// ```ignore (extern-declaration)
3639 /// # fn main() {
3640 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
3641 ///
3642 /// extern "C" {
3643 #[doc = concat!(" fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")]
3644 /// }
3645 ///
3646 #[doc = concat!("let atomic = ", stringify!($atomic_type), "::new(1);")]
3647 ///
3648 /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
3649 /// unsafe {
3650 /// my_atomic_op(atomic.as_ptr());
3651 /// }
3652 /// # }
3653 /// ```
3654 ///
3655 /// [memory model]: self#memory-model-for-atomic-accesses
3656 #[inline]
3657 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
3658 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
3659 #[rustc_never_returns_null_ptr]
3660 pub const fn as_ptr(&self) -> *mut $int_type {
3661 self.v.get()
3662 }
3663 }
3664 }
3665}
3666
3667#[cfg(target_has_atomic_load_store = "8")]
3668atomic_int! {
3669 cfg(target_has_atomic = "8"),
3670 cfg(target_has_atomic_equal_alignment = "8"),
3671 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3672 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3673 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3674 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3675 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3676 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3677 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3678 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3679 rustc_diagnostic_item = "AtomicI8",
3680 "i8",
3681 "",
3682 atomic_min, atomic_max,
3683 1,
3684 i8 AtomicI8
3685}
3686#[cfg(target_has_atomic_load_store = "8")]
3687atomic_int! {
3688 cfg(target_has_atomic = "8"),
3689 cfg(target_has_atomic_equal_alignment = "8"),
3690 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3691 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3692 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3693 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3694 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3695 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3696 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3697 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3698 rustc_diagnostic_item = "AtomicU8",
3699 "u8",
3700 "",
3701 atomic_umin, atomic_umax,
3702 1,
3703 u8 AtomicU8
3704}
3705#[cfg(target_has_atomic_load_store = "16")]
3706atomic_int! {
3707 cfg(target_has_atomic = "16"),
3708 cfg(target_has_atomic_equal_alignment = "16"),
3709 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3710 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3711 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3712 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3713 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3714 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3715 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3716 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3717 rustc_diagnostic_item = "AtomicI16",
3718 "i16",
3719 "",
3720 atomic_min, atomic_max,
3721 2,
3722 i16 AtomicI16
3723}
3724#[cfg(target_has_atomic_load_store = "16")]
3725atomic_int! {
3726 cfg(target_has_atomic = "16"),
3727 cfg(target_has_atomic_equal_alignment = "16"),
3728 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3729 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3730 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3731 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3732 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3733 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3734 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3735 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3736 rustc_diagnostic_item = "AtomicU16",
3737 "u16",
3738 "",
3739 atomic_umin, atomic_umax,
3740 2,
3741 u16 AtomicU16
3742}
3743#[cfg(target_has_atomic_load_store = "32")]
3744atomic_int! {
3745 cfg(target_has_atomic = "32"),
3746 cfg(target_has_atomic_equal_alignment = "32"),
3747 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3748 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3749 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3750 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3751 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3752 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3753 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3754 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3755 rustc_diagnostic_item = "AtomicI32",
3756 "i32",
3757 "",
3758 atomic_min, atomic_max,
3759 4,
3760 i32 AtomicI32
3761}
3762#[cfg(target_has_atomic_load_store = "32")]
3763atomic_int! {
3764 cfg(target_has_atomic = "32"),
3765 cfg(target_has_atomic_equal_alignment = "32"),
3766 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3767 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3768 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3769 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3770 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3771 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3772 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3773 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3774 rustc_diagnostic_item = "AtomicU32",
3775 "u32",
3776 "",
3777 atomic_umin, atomic_umax,
3778 4,
3779 u32 AtomicU32
3780}
3781#[cfg(target_has_atomic_load_store = "64")]
3782atomic_int! {
3783 cfg(target_has_atomic = "64"),
3784 cfg(target_has_atomic_equal_alignment = "64"),
3785 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3786 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3787 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3788 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3789 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3790 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3791 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3792 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3793 rustc_diagnostic_item = "AtomicI64",
3794 "i64",
3795 "",
3796 atomic_min, atomic_max,
3797 8,
3798 i64 AtomicI64
3799}
3800#[cfg(target_has_atomic_load_store = "64")]
3801atomic_int! {
3802 cfg(target_has_atomic = "64"),
3803 cfg(target_has_atomic_equal_alignment = "64"),
3804 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3805 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3806 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3807 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3808 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3809 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3810 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3811 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3812 rustc_diagnostic_item = "AtomicU64",
3813 "u64",
3814 "",
3815 atomic_umin, atomic_umax,
3816 8,
3817 u64 AtomicU64
3818}
3819#[cfg(target_has_atomic_load_store = "128")]
3820atomic_int! {
3821 cfg(target_has_atomic = "128"),
3822 cfg(target_has_atomic_equal_alignment = "128"),
3823 unstable(feature = "integer_atomics", issue = "99069"),
3824 unstable(feature = "integer_atomics", issue = "99069"),
3825 unstable(feature = "integer_atomics", issue = "99069"),
3826 unstable(feature = "integer_atomics", issue = "99069"),
3827 unstable(feature = "integer_atomics", issue = "99069"),
3828 unstable(feature = "integer_atomics", issue = "99069"),
3829 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3830 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3831 rustc_diagnostic_item = "AtomicI128",
3832 "i128",
3833 "#![feature(integer_atomics)]\n\n",
3834 atomic_min, atomic_max,
3835 16,
3836 i128 AtomicI128
3837}
3838#[cfg(target_has_atomic_load_store = "128")]
3839atomic_int! {
3840 cfg(target_has_atomic = "128"),
3841 cfg(target_has_atomic_equal_alignment = "128"),
3842 unstable(feature = "integer_atomics", issue = "99069"),
3843 unstable(feature = "integer_atomics", issue = "99069"),
3844 unstable(feature = "integer_atomics", issue = "99069"),
3845 unstable(feature = "integer_atomics", issue = "99069"),
3846 unstable(feature = "integer_atomics", issue = "99069"),
3847 unstable(feature = "integer_atomics", issue = "99069"),
3848 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3849 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3850 rustc_diagnostic_item = "AtomicU128",
3851 "u128",
3852 "#![feature(integer_atomics)]\n\n",
3853 atomic_umin, atomic_umax,
3854 16,
3855 u128 AtomicU128
3856}
3857
3858#[cfg(target_has_atomic_load_store = "ptr")]
3859macro_rules! atomic_int_ptr_sized {
3860 ( $($target_pointer_width:literal $align:literal)* ) => { $(
3861 #[cfg(target_pointer_width = $target_pointer_width)]
3862 atomic_int! {
3863 cfg(target_has_atomic = "ptr"),
3864 cfg(target_has_atomic_equal_alignment = "ptr"),
3865 stable(feature = "rust1", since = "1.0.0"),
3866 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3867 stable(feature = "atomic_debug", since = "1.3.0"),
3868 stable(feature = "atomic_access", since = "1.15.0"),
3869 stable(feature = "atomic_from", since = "1.23.0"),
3870 stable(feature = "atomic_nand", since = "1.27.0"),
3871 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3872 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3873 rustc_diagnostic_item = "AtomicIsize",
3874 "isize",
3875 "",
3876 atomic_min, atomic_max,
3877 $align,
3878 isize AtomicIsize
3879 }
3880 #[cfg(target_pointer_width = $target_pointer_width)]
3881 atomic_int! {
3882 cfg(target_has_atomic = "ptr"),
3883 cfg(target_has_atomic_equal_alignment = "ptr"),
3884 stable(feature = "rust1", since = "1.0.0"),
3885 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3886 stable(feature = "atomic_debug", since = "1.3.0"),
3887 stable(feature = "atomic_access", since = "1.15.0"),
3888 stable(feature = "atomic_from", since = "1.23.0"),
3889 stable(feature = "atomic_nand", since = "1.27.0"),
3890 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3891 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3892 rustc_diagnostic_item = "AtomicUsize",
3893 "usize",
3894 "",
3895 atomic_umin, atomic_umax,
3896 $align,
3897 usize AtomicUsize
3898 }
3899
3900 /// An [`AtomicIsize`] initialized to `0`.
3901 #[cfg(target_pointer_width = $target_pointer_width)]
3902 #[stable(feature = "rust1", since = "1.0.0")]
3903 #[deprecated(
3904 since = "1.34.0",
3905 note = "the `new` function is now preferred",
3906 suggestion = "AtomicIsize::new(0)",
3907 )]
3908 pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0);
3909
3910 /// An [`AtomicUsize`] initialized to `0`.
3911 #[cfg(target_pointer_width = $target_pointer_width)]
3912 #[stable(feature = "rust1", since = "1.0.0")]
3913 #[deprecated(
3914 since = "1.34.0",
3915 note = "the `new` function is now preferred",
3916 suggestion = "AtomicUsize::new(0)",
3917 )]
3918 pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0);
3919 )* };
3920}
3921
3922#[cfg(target_has_atomic_load_store = "ptr")]
3923atomic_int_ptr_sized! {
3924 "16" 2
3925 "32" 4
3926 "64" 8
3927}
3928
3929#[inline]
3930#[cfg(target_has_atomic)]
3931fn strongest_failure_ordering(order: Ordering) -> Ordering {
3932 match order {
3933 Release => Relaxed,
3934 Relaxed => Relaxed,
3935 SeqCst => SeqCst,
3936 Acquire => Acquire,
3937 AcqRel => Acquire,
3938 }
3939}
3940
3941#[inline]
3942#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3943unsafe fn atomic_store<T: Copy>(dst: *mut T, val: T, order: Ordering) {
3944 // SAFETY: the caller must uphold the safety contract for `atomic_store`.
3945 unsafe {
3946 match order {
3947 Relaxed => intrinsics::atomic_store::<T, { AO::Relaxed }>(dst, val),
3948 Release => intrinsics::atomic_store::<T, { AO::Release }>(dst, val),
3949 SeqCst => intrinsics::atomic_store::<T, { AO::SeqCst }>(dst, val),
3950 Acquire => panic!("there is no such thing as an acquire store"),
3951 AcqRel => panic!("there is no such thing as an acquire-release store"),
3952 }
3953 }
3954}
3955
3956#[inline]
3957#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3958unsafe fn atomic_load<T: Copy>(dst: *const T, order: Ordering) -> T {
3959 // SAFETY: the caller must uphold the safety contract for `atomic_load`.
3960 unsafe {
3961 match order {
3962 Relaxed => intrinsics::atomic_load::<T, { AO::Relaxed }>(dst),
3963 Acquire => intrinsics::atomic_load::<T, { AO::Acquire }>(dst),
3964 SeqCst => intrinsics::atomic_load::<T, { AO::SeqCst }>(dst),
3965 Release => panic!("there is no such thing as a release load"),
3966 AcqRel => panic!("there is no such thing as an acquire-release load"),
3967 }
3968 }
3969}
3970
3971#[inline]
3972#[cfg(target_has_atomic)]
3973#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3974unsafe fn atomic_swap<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3975 // SAFETY: the caller must uphold the safety contract for `atomic_swap`.
3976 unsafe {
3977 match order {
3978 Relaxed => intrinsics::atomic_xchg::<T, { AO::Relaxed }>(dst, val),
3979 Acquire => intrinsics::atomic_xchg::<T, { AO::Acquire }>(dst, val),
3980 Release => intrinsics::atomic_xchg::<T, { AO::Release }>(dst, val),
3981 AcqRel => intrinsics::atomic_xchg::<T, { AO::AcqRel }>(dst, val),
3982 SeqCst => intrinsics::atomic_xchg::<T, { AO::SeqCst }>(dst, val),
3983 }
3984 }
3985}
3986
3987/// Returns the previous value (like __sync_fetch_and_add).
3988#[inline]
3989#[cfg(target_has_atomic)]
3990#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3991unsafe fn atomic_add<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
3992 // SAFETY: the caller must uphold the safety contract for `atomic_add`.
3993 unsafe {
3994 match order {
3995 Relaxed => intrinsics::atomic_xadd::<T, U, { AO::Relaxed }>(dst, val),
3996 Acquire => intrinsics::atomic_xadd::<T, U, { AO::Acquire }>(dst, val),
3997 Release => intrinsics::atomic_xadd::<T, U, { AO::Release }>(dst, val),
3998 AcqRel => intrinsics::atomic_xadd::<T, U, { AO::AcqRel }>(dst, val),
3999 SeqCst => intrinsics::atomic_xadd::<T, U, { AO::SeqCst }>(dst, val),
4000 }
4001 }
4002}
4003
4004/// Returns the previous value (like __sync_fetch_and_sub).
4005#[inline]
4006#[cfg(target_has_atomic)]
4007#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4008unsafe fn atomic_sub<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4009 // SAFETY: the caller must uphold the safety contract for `atomic_sub`.
4010 unsafe {
4011 match order {
4012 Relaxed => intrinsics::atomic_xsub::<T, U, { AO::Relaxed }>(dst, val),
4013 Acquire => intrinsics::atomic_xsub::<T, U, { AO::Acquire }>(dst, val),
4014 Release => intrinsics::atomic_xsub::<T, U, { AO::Release }>(dst, val),
4015 AcqRel => intrinsics::atomic_xsub::<T, U, { AO::AcqRel }>(dst, val),
4016 SeqCst => intrinsics::atomic_xsub::<T, U, { AO::SeqCst }>(dst, val),
4017 }
4018 }
4019}
4020
4021/// Publicly exposed for stdarch; nobody else should use this.
4022#[inline]
4023#[cfg(target_has_atomic)]
4024#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4025#[unstable(feature = "core_intrinsics", issue = "none")]
4026#[doc(hidden)]
4027pub unsafe fn atomic_compare_exchange<T: Copy>(
4028 dst: *mut T,
4029 old: T,
4030 new: T,
4031 success: Ordering,
4032 failure: Ordering,
4033) -> Result<T, T> {
4034 // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`.
4035 let (val, ok) = unsafe {
4036 match (success, failure) {
4037 (Relaxed, Relaxed) => {
4038 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4039 }
4040 (Relaxed, Acquire) => {
4041 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4042 }
4043 (Relaxed, SeqCst) => {
4044 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4045 }
4046 (Acquire, Relaxed) => {
4047 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4048 }
4049 (Acquire, Acquire) => {
4050 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4051 }
4052 (Acquire, SeqCst) => {
4053 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4054 }
4055 (Release, Relaxed) => {
4056 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4057 }
4058 (Release, Acquire) => {
4059 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4060 }
4061 (Release, SeqCst) => {
4062 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4063 }
4064 (AcqRel, Relaxed) => {
4065 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4066 }
4067 (AcqRel, Acquire) => {
4068 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4069 }
4070 (AcqRel, SeqCst) => {
4071 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4072 }
4073 (SeqCst, Relaxed) => {
4074 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4075 }
4076 (SeqCst, Acquire) => {
4077 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4078 }
4079 (SeqCst, SeqCst) => {
4080 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4081 }
4082 (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
4083 (_, Release) => panic!("there is no such thing as a release failure ordering"),
4084 }
4085 };
4086 if ok { Ok(val) } else { Err(val) }
4087}
4088
4089#[inline]
4090#[cfg(target_has_atomic)]
4091#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4092unsafe fn atomic_compare_exchange_weak<T: Copy>(
4093 dst: *mut T,
4094 old: T,
4095 new: T,
4096 success: Ordering,
4097 failure: Ordering,
4098) -> Result<T, T> {
4099 // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`.
4100 let (val, ok) = unsafe {
4101 match (success, failure) {
4102 (Relaxed, Relaxed) => {
4103 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4104 }
4105 (Relaxed, Acquire) => {
4106 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4107 }
4108 (Relaxed, SeqCst) => {
4109 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4110 }
4111 (Acquire, Relaxed) => {
4112 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4113 }
4114 (Acquire, Acquire) => {
4115 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4116 }
4117 (Acquire, SeqCst) => {
4118 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4119 }
4120 (Release, Relaxed) => {
4121 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4122 }
4123 (Release, Acquire) => {
4124 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4125 }
4126 (Release, SeqCst) => {
4127 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4128 }
4129 (AcqRel, Relaxed) => {
4130 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4131 }
4132 (AcqRel, Acquire) => {
4133 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4134 }
4135 (AcqRel, SeqCst) => {
4136 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4137 }
4138 (SeqCst, Relaxed) => {
4139 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4140 }
4141 (SeqCst, Acquire) => {
4142 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4143 }
4144 (SeqCst, SeqCst) => {
4145 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4146 }
4147 (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
4148 (_, Release) => panic!("there is no such thing as a release failure ordering"),
4149 }
4150 };
4151 if ok { Ok(val) } else { Err(val) }
4152}
4153
4154#[inline]
4155#[cfg(target_has_atomic)]
4156#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4157unsafe fn atomic_and<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4158 // SAFETY: the caller must uphold the safety contract for `atomic_and`
4159 unsafe {
4160 match order {
4161 Relaxed => intrinsics::atomic_and::<T, U, { AO::Relaxed }>(dst, val),
4162 Acquire => intrinsics::atomic_and::<T, U, { AO::Acquire }>(dst, val),
4163 Release => intrinsics::atomic_and::<T, U, { AO::Release }>(dst, val),
4164 AcqRel => intrinsics::atomic_and::<T, U, { AO::AcqRel }>(dst, val),
4165 SeqCst => intrinsics::atomic_and::<T, U, { AO::SeqCst }>(dst, val),
4166 }
4167 }
4168}
4169
4170#[inline]
4171#[cfg(target_has_atomic)]
4172#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4173unsafe fn atomic_nand<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4174 // SAFETY: the caller must uphold the safety contract for `atomic_nand`
4175 unsafe {
4176 match order {
4177 Relaxed => intrinsics::atomic_nand::<T, U, { AO::Relaxed }>(dst, val),
4178 Acquire => intrinsics::atomic_nand::<T, U, { AO::Acquire }>(dst, val),
4179 Release => intrinsics::atomic_nand::<T, U, { AO::Release }>(dst, val),
4180 AcqRel => intrinsics::atomic_nand::<T, U, { AO::AcqRel }>(dst, val),
4181 SeqCst => intrinsics::atomic_nand::<T, U, { AO::SeqCst }>(dst, val),
4182 }
4183 }
4184}
4185
4186#[inline]
4187#[cfg(target_has_atomic)]
4188#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4189unsafe fn atomic_or<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4190 // SAFETY: the caller must uphold the safety contract for `atomic_or`
4191 unsafe {
4192 match order {
4193 SeqCst => intrinsics::atomic_or::<T, U, { AO::SeqCst }>(dst, val),
4194 Acquire => intrinsics::atomic_or::<T, U, { AO::Acquire }>(dst, val),
4195 Release => intrinsics::atomic_or::<T, U, { AO::Release }>(dst, val),
4196 AcqRel => intrinsics::atomic_or::<T, U, { AO::AcqRel }>(dst, val),
4197 Relaxed => intrinsics::atomic_or::<T, U, { AO::Relaxed }>(dst, val),
4198 }
4199 }
4200}
4201
4202#[inline]
4203#[cfg(target_has_atomic)]
4204#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4205unsafe fn atomic_xor<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4206 // SAFETY: the caller must uphold the safety contract for `atomic_xor`
4207 unsafe {
4208 match order {
4209 SeqCst => intrinsics::atomic_xor::<T, U, { AO::SeqCst }>(dst, val),
4210 Acquire => intrinsics::atomic_xor::<T, U, { AO::Acquire }>(dst, val),
4211 Release => intrinsics::atomic_xor::<T, U, { AO::Release }>(dst, val),
4212 AcqRel => intrinsics::atomic_xor::<T, U, { AO::AcqRel }>(dst, val),
4213 Relaxed => intrinsics::atomic_xor::<T, U, { AO::Relaxed }>(dst, val),
4214 }
4215 }
4216}
4217
4218/// Updates `*dst` to the max value of `val` and the old value (signed comparison)
4219#[inline]
4220#[cfg(target_has_atomic)]
4221#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4222unsafe fn atomic_max<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4223 // SAFETY: the caller must uphold the safety contract for `atomic_max`
4224 unsafe {
4225 match order {
4226 Relaxed => intrinsics::atomic_max::<T, { AO::Relaxed }>(dst, val),
4227 Acquire => intrinsics::atomic_max::<T, { AO::Acquire }>(dst, val),
4228 Release => intrinsics::atomic_max::<T, { AO::Release }>(dst, val),
4229 AcqRel => intrinsics::atomic_max::<T, { AO::AcqRel }>(dst, val),
4230 SeqCst => intrinsics::atomic_max::<T, { AO::SeqCst }>(dst, val),
4231 }
4232 }
4233}
4234
4235/// Updates `*dst` to the min value of `val` and the old value (signed comparison)
4236#[inline]
4237#[cfg(target_has_atomic)]
4238#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4239unsafe fn atomic_min<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4240 // SAFETY: the caller must uphold the safety contract for `atomic_min`
4241 unsafe {
4242 match order {
4243 Relaxed => intrinsics::atomic_min::<T, { AO::Relaxed }>(dst, val),
4244 Acquire => intrinsics::atomic_min::<T, { AO::Acquire }>(dst, val),
4245 Release => intrinsics::atomic_min::<T, { AO::Release }>(dst, val),
4246 AcqRel => intrinsics::atomic_min::<T, { AO::AcqRel }>(dst, val),
4247 SeqCst => intrinsics::atomic_min::<T, { AO::SeqCst }>(dst, val),
4248 }
4249 }
4250}
4251
4252/// Updates `*dst` to the max value of `val` and the old value (unsigned comparison)
4253#[inline]
4254#[cfg(target_has_atomic)]
4255#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4256unsafe fn atomic_umax<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4257 // SAFETY: the caller must uphold the safety contract for `atomic_umax`
4258 unsafe {
4259 match order {
4260 Relaxed => intrinsics::atomic_umax::<T, { AO::Relaxed }>(dst, val),
4261 Acquire => intrinsics::atomic_umax::<T, { AO::Acquire }>(dst, val),
4262 Release => intrinsics::atomic_umax::<T, { AO::Release }>(dst, val),
4263 AcqRel => intrinsics::atomic_umax::<T, { AO::AcqRel }>(dst, val),
4264 SeqCst => intrinsics::atomic_umax::<T, { AO::SeqCst }>(dst, val),
4265 }
4266 }
4267}
4268
4269/// Updates `*dst` to the min value of `val` and the old value (unsigned comparison)
4270#[inline]
4271#[cfg(target_has_atomic)]
4272#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4273unsafe fn atomic_umin<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4274 // SAFETY: the caller must uphold the safety contract for `atomic_umin`
4275 unsafe {
4276 match order {
4277 Relaxed => intrinsics::atomic_umin::<T, { AO::Relaxed }>(dst, val),
4278 Acquire => intrinsics::atomic_umin::<T, { AO::Acquire }>(dst, val),
4279 Release => intrinsics::atomic_umin::<T, { AO::Release }>(dst, val),
4280 AcqRel => intrinsics::atomic_umin::<T, { AO::AcqRel }>(dst, val),
4281 SeqCst => intrinsics::atomic_umin::<T, { AO::SeqCst }>(dst, val),
4282 }
4283 }
4284}
4285
4286/// An atomic fence.
4287///
4288/// Fences create synchronization between themselves and atomic operations or fences in other
4289/// threads. To achieve this, a fence prevents the compiler and CPU from reordering certain types of
4290/// memory operations around it.
4291///
4292/// A fence 'A' which has (at least) [`Release`] ordering semantics, synchronizes
4293/// with a fence 'B' with (at least) [`Acquire`] semantics, if and only if there
4294/// exist operations X and Y, both operating on some atomic object 'm' such
4295/// that A is sequenced before X, Y is sequenced before B and Y observes
4296/// the change to m. This provides a happens-before dependence between A and B.
4297///
4298/// ```text
4299/// Thread 1 Thread 2
4300///
4301/// fence(Release); A --------------
4302/// m.store(3, Relaxed); X --------- |
4303/// | |
4304/// | |
4305/// -------------> Y if m.load(Relaxed) == 3 {
4306/// |-------> B fence(Acquire);
4307/// ...
4308/// }
4309/// ```
4310///
4311/// Note that in the example above, it is crucial that the accesses to `m` are atomic. Fences cannot
4312/// be used to establish synchronization among non-atomic accesses in different threads. However,
4313/// thanks to the happens-before relationship between A and B, any non-atomic accesses that
4314/// happen-before A are now also properly synchronized with any non-atomic accesses that
4315/// happen-after B.
4316///
4317/// Atomic operations with [`Release`] or [`Acquire`] semantics can also synchronize
4318/// with a fence.
4319///
4320/// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`]
4321/// and [`Release`] semantics, participates in the global program order of the
4322/// other [`SeqCst`] operations and/or fences.
4323///
4324/// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings.
4325///
4326/// # Panics
4327///
4328/// Panics if `order` is [`Relaxed`].
4329///
4330/// # Examples
4331///
4332/// ```
4333/// use std::sync::atomic::AtomicBool;
4334/// use std::sync::atomic::fence;
4335/// use std::sync::atomic::Ordering;
4336///
4337/// // A mutual exclusion primitive based on spinlock.
4338/// pub struct Mutex {
4339/// flag: AtomicBool,
4340/// }
4341///
4342/// impl Mutex {
4343/// pub fn new() -> Mutex {
4344/// Mutex {
4345/// flag: AtomicBool::new(false),
4346/// }
4347/// }
4348///
4349/// pub fn lock(&self) {
4350/// // Wait until the old value is `false`.
4351/// while self
4352/// .flag
4353/// .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
4354/// .is_err()
4355/// {}
4356/// // This fence synchronizes-with store in `unlock`.
4357/// fence(Ordering::Acquire);
4358/// }
4359///
4360/// pub fn unlock(&self) {
4361/// self.flag.store(false, Ordering::Release);
4362/// }
4363/// }
4364/// ```
4365#[inline]
4366#[stable(feature = "rust1", since = "1.0.0")]
4367#[rustc_diagnostic_item = "fence"]
4368#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4369pub fn fence(order: Ordering) {
4370 // SAFETY: using an atomic fence is safe.
4371 unsafe {
4372 match order {
4373 Acquire => intrinsics::atomic_fence::<{ AO::Acquire }>(),
4374 Release => intrinsics::atomic_fence::<{ AO::Release }>(),
4375 AcqRel => intrinsics::atomic_fence::<{ AO::AcqRel }>(),
4376 SeqCst => intrinsics::atomic_fence::<{ AO::SeqCst }>(),
4377 Relaxed => panic!("there is no such thing as a relaxed fence"),
4378 }
4379 }
4380}
4381
4382/// A "compiler-only" atomic fence.
4383///
4384/// Like [`fence`], this function establishes synchronization with other atomic operations and
4385/// fences. However, unlike [`fence`], `compiler_fence` only establishes synchronization with
4386/// operations *in the same thread*. This may at first sound rather useless, since code within a
4387/// thread is typically already totally ordered and does not need any further synchronization.
4388/// However, there are cases where code can run on the same thread without being ordered:
4389/// - The most common case is that of a *signal handler*: a signal handler runs in the same thread
4390/// as the code it interrupted, but it is not ordered with respect to that code. `compiler_fence`
4391/// can be used to establish synchronization between a thread and its signal handler, the same way
4392/// that `fence` can be used to establish synchronization across threads.
4393/// - Similar situations can arise in embedded programming with interrupt handlers, or in custom
4394/// implementations of preemptive green threads. In general, `compiler_fence` can establish
4395/// synchronization with code that is guaranteed to run on the same hardware CPU.
4396///
4397/// See [`fence`] for how a fence can be used to achieve synchronization. Note that just like
4398/// [`fence`], synchronization still requires atomic operations to be used in both threads -- it is
4399/// not possible to perform synchronization entirely with fences and non-atomic operations.
4400///
4401/// `compiler_fence` does not emit any machine code, but restricts the kinds of memory re-ordering
4402/// the compiler is allowed to do. `compiler_fence` corresponds to [`atomic_signal_fence`] in C and
4403/// C++.
4404///
4405/// [`atomic_signal_fence`]: https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence
4406///
4407/// # Panics
4408///
4409/// Panics if `order` is [`Relaxed`].
4410///
4411/// # Examples
4412///
4413/// Without the two `compiler_fence` calls, the read of `IMPORTANT_VARIABLE` in `signal_handler`
4414/// is *undefined behavior* due to a data race, despite everything happening in a single thread.
4415/// This is because the signal handler is considered to run concurrently with its associated
4416/// thread, and explicit synchronization is required to pass data between a thread and its
4417/// signal handler. The code below uses two `compiler_fence` calls to establish the usual
4418/// release-acquire synchronization pattern (see [`fence`] for an image).
4419///
4420/// ```
4421/// use std::sync::atomic::AtomicBool;
4422/// use std::sync::atomic::Ordering;
4423/// use std::sync::atomic::compiler_fence;
4424///
4425/// static mut IMPORTANT_VARIABLE: usize = 0;
4426/// static IS_READY: AtomicBool = AtomicBool::new(false);
4427///
4428/// fn main() {
4429/// unsafe { IMPORTANT_VARIABLE = 42 };
4430/// // Marks earlier writes as being released with future relaxed stores.
4431/// compiler_fence(Ordering::Release);
4432/// IS_READY.store(true, Ordering::Relaxed);
4433/// }
4434///
4435/// fn signal_handler() {
4436/// if IS_READY.load(Ordering::Relaxed) {
4437/// // Acquires writes that were released with relaxed stores that we read from.
4438/// compiler_fence(Ordering::Acquire);
4439/// assert_eq!(unsafe { IMPORTANT_VARIABLE }, 42);
4440/// }
4441/// }
4442/// ```
4443#[inline]
4444#[stable(feature = "compiler_fences", since = "1.21.0")]
4445#[rustc_diagnostic_item = "compiler_fence"]
4446#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4447pub fn compiler_fence(order: Ordering) {
4448 // SAFETY: using an atomic fence is safe.
4449 unsafe {
4450 match order {
4451 Acquire => intrinsics::atomic_singlethreadfence::<{ AO::Acquire }>(),
4452 Release => intrinsics::atomic_singlethreadfence::<{ AO::Release }>(),
4453 AcqRel => intrinsics::atomic_singlethreadfence::<{ AO::AcqRel }>(),
4454 SeqCst => intrinsics::atomic_singlethreadfence::<{ AO::SeqCst }>(),
4455 Relaxed => panic!("there is no such thing as a relaxed fence"),
4456 }
4457 }
4458}
4459
4460#[cfg(target_has_atomic_load_store = "8")]
4461#[stable(feature = "atomic_debug", since = "1.3.0")]
4462impl fmt::Debug for AtomicBool {
4463 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4464 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4465 }
4466}
4467
4468#[cfg(target_has_atomic_load_store = "ptr")]
4469#[stable(feature = "atomic_debug", since = "1.3.0")]
4470impl<T> fmt::Debug for AtomicPtr<T> {
4471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4472 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4473 }
4474}
4475
4476#[cfg(target_has_atomic_load_store = "ptr")]
4477#[stable(feature = "atomic_pointer", since = "1.24.0")]
4478impl<T> fmt::Pointer for AtomicPtr<T> {
4479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4480 fmt::Pointer::fmt(&self.load(Ordering::Relaxed), f)
4481 }
4482}
4483
4484/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock").
4485///
4486/// This function is deprecated in favor of [`hint::spin_loop`].
4487///
4488/// [`hint::spin_loop`]: crate::hint::spin_loop
4489#[inline]
4490#[stable(feature = "spin_loop_hint", since = "1.24.0")]
4491#[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")]
4492pub fn spin_loop_hint() {
4493 spin_loop()
4494}