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 /// # Examples
1562 ///
1563 /// ```
1564 /// #![feature(atomic_from_mut)]
1565 /// use std::sync::atomic::{AtomicPtr, Ordering};
1566 ///
1567 /// let mut data = 123;
1568 /// let mut some_ptr = &mut data as *mut i32;
1569 /// let a = AtomicPtr::from_mut(&mut some_ptr);
1570 /// let mut other_data = 456;
1571 /// a.store(&mut other_data, Ordering::Relaxed);
1572 /// assert_eq!(unsafe { *some_ptr }, 456);
1573 /// ```
1574 #[inline]
1575 #[cfg(target_has_atomic_equal_alignment = "ptr")]
1576 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1577 pub fn from_mut(v: &mut *mut T) -> &mut Self {
1578 let [] = [(); align_of::<AtomicPtr<()>>() - align_of::<*mut ()>()];
1579 // SAFETY:
1580 // - the mutable reference guarantees unique ownership.
1581 // - the alignment of `*mut T` and `Self` is the same on all platforms
1582 // supported by rust, as verified above.
1583 unsafe { &mut *(v as *mut *mut T as *mut Self) }
1584 }
1585
1586 /// Gets non-atomic access to a `&mut [AtomicPtr]` slice.
1587 ///
1588 /// This is safe because the mutable reference guarantees that no other threads are
1589 /// concurrently accessing the atomic data.
1590 ///
1591 /// # Examples
1592 ///
1593 /// ```ignore-wasm
1594 /// #![feature(atomic_from_mut)]
1595 /// use std::ptr::null_mut;
1596 /// use std::sync::atomic::{AtomicPtr, Ordering};
1597 ///
1598 /// let mut some_ptrs = [const { AtomicPtr::new(null_mut::<String>()) }; 10];
1599 ///
1600 /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs);
1601 /// assert_eq!(view, [null_mut::<String>(); 10]);
1602 /// view
1603 /// .iter_mut()
1604 /// .enumerate()
1605 /// .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}"))));
1606 ///
1607 /// std::thread::scope(|s| {
1608 /// for ptr in &some_ptrs {
1609 /// s.spawn(move || {
1610 /// let ptr = ptr.load(Ordering::Relaxed);
1611 /// assert!(!ptr.is_null());
1612 ///
1613 /// let name = unsafe { Box::from_raw(ptr) };
1614 /// println!("Hello, {name}!");
1615 /// });
1616 /// }
1617 /// });
1618 /// ```
1619 #[inline]
1620 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1621 pub fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T] {
1622 // SAFETY: the mutable reference guarantees unique ownership.
1623 unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) }
1624 }
1625
1626 /// Gets atomic access to a slice of pointers.
1627 ///
1628 /// # Examples
1629 ///
1630 /// ```ignore-wasm
1631 /// #![feature(atomic_from_mut)]
1632 /// use std::ptr::null_mut;
1633 /// use std::sync::atomic::{AtomicPtr, Ordering};
1634 ///
1635 /// let mut some_ptrs = [null_mut::<String>(); 10];
1636 /// let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs);
1637 /// std::thread::scope(|s| {
1638 /// for i in 0..a.len() {
1639 /// s.spawn(move || {
1640 /// let name = Box::new(format!("thread{i}"));
1641 /// a[i].store(Box::into_raw(name), Ordering::Relaxed);
1642 /// });
1643 /// }
1644 /// });
1645 /// for p in some_ptrs {
1646 /// assert!(!p.is_null());
1647 /// let name = unsafe { Box::from_raw(p) };
1648 /// println!("Hello, {name}!");
1649 /// }
1650 /// ```
1651 #[inline]
1652 #[cfg(target_has_atomic_equal_alignment = "ptr")]
1653 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1654 pub fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self] {
1655 // SAFETY:
1656 // - the mutable reference guarantees unique ownership.
1657 // - the alignment of `*mut T` and `Self` is the same on all platforms
1658 // supported by rust, as verified above.
1659 unsafe { &mut *(v as *mut [*mut T] as *mut [Self]) }
1660 }
1661
1662 /// Consumes the atomic and returns the contained value.
1663 ///
1664 /// This is safe because passing `self` by value guarantees that no other threads are
1665 /// concurrently accessing the atomic data.
1666 ///
1667 /// # Examples
1668 ///
1669 /// ```
1670 /// use std::sync::atomic::AtomicPtr;
1671 ///
1672 /// let mut data = 5;
1673 /// let atomic_ptr = AtomicPtr::new(&mut data);
1674 /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5);
1675 /// ```
1676 #[inline]
1677 #[stable(feature = "atomic_access", since = "1.15.0")]
1678 #[rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0")]
1679 pub const fn into_inner(self) -> *mut T {
1680 self.p.into_inner()
1681 }
1682
1683 /// Loads a value from the pointer.
1684 ///
1685 /// `load` takes an [`Ordering`] argument which describes the memory ordering
1686 /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
1687 ///
1688 /// # Panics
1689 ///
1690 /// Panics if `order` is [`Release`] or [`AcqRel`].
1691 ///
1692 /// # Examples
1693 ///
1694 /// ```
1695 /// use std::sync::atomic::{AtomicPtr, Ordering};
1696 ///
1697 /// let ptr = &mut 5;
1698 /// let some_ptr = AtomicPtr::new(ptr);
1699 ///
1700 /// let value = some_ptr.load(Ordering::Relaxed);
1701 /// ```
1702 #[inline]
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1705 pub fn load(&self, order: Ordering) -> *mut T {
1706 // SAFETY: data races are prevented by atomic intrinsics.
1707 unsafe { atomic_load(self.p.get(), order) }
1708 }
1709
1710 /// Stores a value into the pointer.
1711 ///
1712 /// `store` takes an [`Ordering`] argument which describes the memory ordering
1713 /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
1714 ///
1715 /// # Panics
1716 ///
1717 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
1718 ///
1719 /// # Examples
1720 ///
1721 /// ```
1722 /// use std::sync::atomic::{AtomicPtr, Ordering};
1723 ///
1724 /// let ptr = &mut 5;
1725 /// let some_ptr = AtomicPtr::new(ptr);
1726 ///
1727 /// let other_ptr = &mut 10;
1728 ///
1729 /// some_ptr.store(other_ptr, Ordering::Relaxed);
1730 /// ```
1731 #[inline]
1732 #[stable(feature = "rust1", since = "1.0.0")]
1733 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1734 pub fn store(&self, ptr: *mut T, order: Ordering) {
1735 // SAFETY: data races are prevented by atomic intrinsics.
1736 unsafe {
1737 atomic_store(self.p.get(), ptr, order);
1738 }
1739 }
1740
1741 /// Stores a value into the pointer, returning the previous value.
1742 ///
1743 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
1744 /// of this operation. All ordering modes are possible. Note that using
1745 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1746 /// using [`Release`] makes the load part [`Relaxed`].
1747 ///
1748 /// **Note:** This method is only available on platforms that support atomic
1749 /// operations on pointers.
1750 ///
1751 /// # Examples
1752 ///
1753 /// ```
1754 /// use std::sync::atomic::{AtomicPtr, Ordering};
1755 ///
1756 /// let ptr = &mut 5;
1757 /// let some_ptr = AtomicPtr::new(ptr);
1758 ///
1759 /// let other_ptr = &mut 10;
1760 ///
1761 /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed);
1762 /// ```
1763 #[inline]
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 #[cfg(target_has_atomic = "ptr")]
1766 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1767 pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T {
1768 // SAFETY: data races are prevented by atomic intrinsics.
1769 unsafe { atomic_swap(self.p.get(), ptr, order) }
1770 }
1771
1772 /// Stores a value into the pointer if the current value is the same as the `current` value.
1773 ///
1774 /// The return value is always the previous value. If it is equal to `current`, then the value
1775 /// was updated.
1776 ///
1777 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
1778 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
1779 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
1780 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
1781 /// happens, and using [`Release`] makes the load part [`Relaxed`].
1782 ///
1783 /// **Note:** This method is only available on platforms that support atomic
1784 /// operations on pointers.
1785 ///
1786 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
1787 ///
1788 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
1789 /// memory orderings:
1790 ///
1791 /// Original | Success | Failure
1792 /// -------- | ------- | -------
1793 /// Relaxed | Relaxed | Relaxed
1794 /// Acquire | Acquire | Acquire
1795 /// Release | Release | Relaxed
1796 /// AcqRel | AcqRel | Acquire
1797 /// SeqCst | SeqCst | SeqCst
1798 ///
1799 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
1800 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
1801 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
1802 /// rather than to infer success vs failure based on the value that was read.
1803 ///
1804 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
1805 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
1806 /// which allows the compiler to generate better assembly code when the compare and swap
1807 /// is used in a loop.
1808 ///
1809 /// # Examples
1810 ///
1811 /// ```
1812 /// use std::sync::atomic::{AtomicPtr, Ordering};
1813 ///
1814 /// let ptr = &mut 5;
1815 /// let some_ptr = AtomicPtr::new(ptr);
1816 ///
1817 /// let other_ptr = &mut 10;
1818 ///
1819 /// let value = some_ptr.compare_and_swap(ptr, other_ptr, Ordering::Relaxed);
1820 /// ```
1821 #[inline]
1822 #[stable(feature = "rust1", since = "1.0.0")]
1823 #[deprecated(
1824 since = "1.50.0",
1825 note = "Use `compare_exchange` or `compare_exchange_weak` instead"
1826 )]
1827 #[cfg(target_has_atomic = "ptr")]
1828 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1829 pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
1830 match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
1831 Ok(x) => x,
1832 Err(x) => x,
1833 }
1834 }
1835
1836 /// Stores a value into the pointer if the current value is the same as the `current` value.
1837 ///
1838 /// The return value is a result indicating whether the new value was written and containing
1839 /// the previous value. On success this value is guaranteed to be equal to `current`.
1840 ///
1841 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
1842 /// ordering of this operation. `success` describes the required ordering for the
1843 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1844 /// `failure` describes the required ordering for the load operation that takes place when
1845 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1846 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1847 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1848 ///
1849 /// **Note:** This method is only available on platforms that support atomic
1850 /// operations on pointers.
1851 ///
1852 /// # Examples
1853 ///
1854 /// ```
1855 /// use std::sync::atomic::{AtomicPtr, Ordering};
1856 ///
1857 /// let ptr = &mut 5;
1858 /// let some_ptr = AtomicPtr::new(ptr);
1859 ///
1860 /// let other_ptr = &mut 10;
1861 ///
1862 /// let value = some_ptr.compare_exchange(ptr, other_ptr,
1863 /// Ordering::SeqCst, Ordering::Relaxed);
1864 /// ```
1865 ///
1866 /// # Considerations
1867 ///
1868 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1869 /// of CAS operations. In particular, a load of the value followed by a successful
1870 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1871 /// changed the value in the interim. This is usually important when the *equality* check in
1872 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1873 /// does not necessarily imply identity. This is a particularly common case for pointers, as
1874 /// a pointer holding the same address does not imply that the same object exists at that
1875 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
1876 ///
1877 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1878 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1879 #[inline]
1880 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1881 #[cfg(target_has_atomic = "ptr")]
1882 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1883 pub fn compare_exchange(
1884 &self,
1885 current: *mut T,
1886 new: *mut T,
1887 success: Ordering,
1888 failure: Ordering,
1889 ) -> Result<*mut T, *mut T> {
1890 // SAFETY: data races are prevented by atomic intrinsics.
1891 unsafe { atomic_compare_exchange(self.p.get(), current, new, success, failure) }
1892 }
1893
1894 /// Stores a value into the pointer if the current value is the same as the `current` value.
1895 ///
1896 /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the
1897 /// comparison succeeds, which can result in more efficient code on some platforms. The
1898 /// return value is a result indicating whether the new value was written and containing the
1899 /// previous value.
1900 ///
1901 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
1902 /// ordering of this operation. `success` describes the required ordering for the
1903 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1904 /// `failure` describes the required ordering for the load operation that takes place when
1905 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1906 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1907 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
1908 ///
1909 /// **Note:** This method is only available on platforms that support atomic
1910 /// operations on pointers.
1911 ///
1912 /// # Examples
1913 ///
1914 /// ```
1915 /// use std::sync::atomic::{AtomicPtr, Ordering};
1916 ///
1917 /// let some_ptr = AtomicPtr::new(&mut 5);
1918 ///
1919 /// let new = &mut 10;
1920 /// let mut old = some_ptr.load(Ordering::Relaxed);
1921 /// loop {
1922 /// match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
1923 /// Ok(_) => break,
1924 /// Err(x) => old = x,
1925 /// }
1926 /// }
1927 /// ```
1928 ///
1929 /// # Considerations
1930 ///
1931 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
1932 /// of CAS operations. In particular, a load of the value followed by a successful
1933 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
1934 /// changed the value in the interim. This is usually important when the *equality* check in
1935 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
1936 /// does not necessarily imply identity. This is a particularly common case for pointers, as
1937 /// a pointer holding the same address does not imply that the same object exists at that
1938 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
1939 ///
1940 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1941 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1942 #[inline]
1943 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1944 #[cfg(target_has_atomic = "ptr")]
1945 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
1946 pub fn compare_exchange_weak(
1947 &self,
1948 current: *mut T,
1949 new: *mut T,
1950 success: Ordering,
1951 failure: Ordering,
1952 ) -> Result<*mut T, *mut T> {
1953 // SAFETY: This intrinsic is unsafe because it operates on a raw pointer
1954 // but we know for sure that the pointer is valid (we just got it from
1955 // an `UnsafeCell` that we have by reference) and the atomic operation
1956 // itself allows us to safely mutate the `UnsafeCell` contents.
1957 unsafe { atomic_compare_exchange_weak(self.p.get(), current, new, success, failure) }
1958 }
1959
1960 /// Fetches the value, and applies a function to it that returns an optional
1961 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1962 /// returned `Some(_)`, else `Err(previous_value)`.
1963 ///
1964 /// Note: This may call the function multiple times if the value has been
1965 /// changed from other threads in the meantime, as long as the function
1966 /// returns `Some(_)`, but the function will have been applied only once to
1967 /// the stored value.
1968 ///
1969 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
1970 /// ordering of this operation. The first describes the required ordering for
1971 /// when the operation finally succeeds while the second describes the
1972 /// required ordering for loads. These correspond to the success and failure
1973 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
1974 ///
1975 /// Using [`Acquire`] as success ordering makes the store part of this
1976 /// operation [`Relaxed`], and using [`Release`] makes the final successful
1977 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1978 /// [`Acquire`] or [`Relaxed`].
1979 ///
1980 /// **Note:** This method is only available on platforms that support atomic
1981 /// operations on pointers.
1982 ///
1983 /// # Considerations
1984 ///
1985 /// This method is not magic; it is not provided by the hardware, and does not act like a
1986 /// critical section or mutex.
1987 ///
1988 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
1989 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
1990 /// which is a particularly common pitfall for pointers!
1991 ///
1992 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
1993 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
1994 ///
1995 /// # Examples
1996 ///
1997 /// ```rust
1998 /// use std::sync::atomic::{AtomicPtr, Ordering};
1999 ///
2000 /// let ptr: *mut _ = &mut 5;
2001 /// let some_ptr = AtomicPtr::new(ptr);
2002 ///
2003 /// let new: *mut _ = &mut 10;
2004 /// assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
2005 /// let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
2006 /// if x == ptr {
2007 /// Some(new)
2008 /// } else {
2009 /// None
2010 /// }
2011 /// });
2012 /// assert_eq!(result, Ok(ptr));
2013 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2014 /// ```
2015 #[inline]
2016 #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
2017 #[cfg(target_has_atomic = "ptr")]
2018 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2019 pub fn fetch_update<F>(
2020 &self,
2021 set_order: Ordering,
2022 fetch_order: Ordering,
2023 mut f: F,
2024 ) -> Result<*mut T, *mut T>
2025 where
2026 F: FnMut(*mut T) -> Option<*mut T>,
2027 {
2028 let mut prev = self.load(fetch_order);
2029 while let Some(next) = f(prev) {
2030 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
2031 x @ Ok(_) => return x,
2032 Err(next_prev) => prev = next_prev,
2033 }
2034 }
2035 Err(prev)
2036 }
2037 /// Fetches the value, and applies a function to it that returns an optional
2038 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
2039 /// returned `Some(_)`, else `Err(previous_value)`.
2040 ///
2041 /// See also: [`update`](`AtomicPtr::update`).
2042 ///
2043 /// Note: This may call the function multiple times if the value has been
2044 /// changed from other threads in the meantime, as long as the function
2045 /// returns `Some(_)`, but the function will have been applied only once to
2046 /// the stored value.
2047 ///
2048 /// `try_update` takes two [`Ordering`] arguments to describe the memory
2049 /// ordering of this operation. The first describes the required ordering for
2050 /// when the operation finally succeeds while the second describes the
2051 /// required ordering for loads. These correspond to the success and failure
2052 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2053 ///
2054 /// Using [`Acquire`] as success ordering makes the store part of this
2055 /// operation [`Relaxed`], and using [`Release`] makes the final successful
2056 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
2057 /// [`Acquire`] or [`Relaxed`].
2058 ///
2059 /// **Note:** This method is only available on platforms that support atomic
2060 /// operations on pointers.
2061 ///
2062 /// # Considerations
2063 ///
2064 /// This method is not magic; it is not provided by the hardware, and does not act like a
2065 /// critical section or mutex.
2066 ///
2067 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2068 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2069 /// which is a particularly common pitfall for pointers!
2070 ///
2071 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2072 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2073 ///
2074 /// # Examples
2075 ///
2076 /// ```rust
2077 /// #![feature(atomic_try_update)]
2078 /// use std::sync::atomic::{AtomicPtr, Ordering};
2079 ///
2080 /// let ptr: *mut _ = &mut 5;
2081 /// let some_ptr = AtomicPtr::new(ptr);
2082 ///
2083 /// let new: *mut _ = &mut 10;
2084 /// assert_eq!(some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
2085 /// let result = some_ptr.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
2086 /// if x == ptr {
2087 /// Some(new)
2088 /// } else {
2089 /// None
2090 /// }
2091 /// });
2092 /// assert_eq!(result, Ok(ptr));
2093 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2094 /// ```
2095 #[inline]
2096 #[unstable(feature = "atomic_try_update", issue = "135894")]
2097 #[cfg(target_has_atomic = "ptr")]
2098 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2099 pub fn try_update(
2100 &self,
2101 set_order: Ordering,
2102 fetch_order: Ordering,
2103 f: impl FnMut(*mut T) -> Option<*mut T>,
2104 ) -> Result<*mut T, *mut T> {
2105 // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
2106 // when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
2107 self.fetch_update(set_order, fetch_order, f)
2108 }
2109
2110 /// Fetches the value, applies a function to it that it return a new value.
2111 /// The new value is stored and the old value is returned.
2112 ///
2113 /// See also: [`try_update`](`AtomicPtr::try_update`).
2114 ///
2115 /// Note: This may call the function multiple times if the value has been changed from other threads in
2116 /// the meantime, but the function will have been applied only once to the stored value.
2117 ///
2118 /// `update` takes two [`Ordering`] arguments to describe the memory
2119 /// ordering of this operation. The first describes the required ordering for
2120 /// when the operation finally succeeds while the second describes the
2121 /// required ordering for loads. These correspond to the success and failure
2122 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
2123 ///
2124 /// Using [`Acquire`] as success ordering makes the store part
2125 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
2126 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
2127 ///
2128 /// **Note:** This method is only available on platforms that support atomic
2129 /// operations on pointers.
2130 ///
2131 /// # Considerations
2132 ///
2133 /// This method is not magic; it is not provided by the hardware, and does not act like a
2134 /// critical section or mutex.
2135 ///
2136 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
2137 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem],
2138 /// which is a particularly common pitfall for pointers!
2139 ///
2140 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
2141 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
2142 ///
2143 /// # Examples
2144 ///
2145 /// ```rust
2146 /// #![feature(atomic_try_update)]
2147 ///
2148 /// use std::sync::atomic::{AtomicPtr, Ordering};
2149 ///
2150 /// let ptr: *mut _ = &mut 5;
2151 /// let some_ptr = AtomicPtr::new(ptr);
2152 ///
2153 /// let new: *mut _ = &mut 10;
2154 /// let result = some_ptr.update(Ordering::SeqCst, Ordering::SeqCst, |_| new);
2155 /// assert_eq!(result, ptr);
2156 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
2157 /// ```
2158 #[inline]
2159 #[unstable(feature = "atomic_try_update", issue = "135894")]
2160 #[cfg(target_has_atomic = "8")]
2161 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2162 pub fn update(
2163 &self,
2164 set_order: Ordering,
2165 fetch_order: Ordering,
2166 mut f: impl FnMut(*mut T) -> *mut T,
2167 ) -> *mut T {
2168 let mut prev = self.load(fetch_order);
2169 loop {
2170 match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
2171 Ok(x) => break x,
2172 Err(next_prev) => prev = next_prev,
2173 }
2174 }
2175 }
2176
2177 /// Offsets the pointer's address by adding `val` (in units of `T`),
2178 /// returning the previous pointer.
2179 ///
2180 /// This is equivalent to using [`wrapping_add`] to atomically perform the
2181 /// equivalent of `ptr = ptr.wrapping_add(val);`.
2182 ///
2183 /// This method operates in units of `T`, which means that it cannot be used
2184 /// to offset the pointer by an amount which is not a multiple of
2185 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2186 /// work with a deliberately misaligned pointer. In such cases, you may use
2187 /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead.
2188 ///
2189 /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the
2190 /// memory ordering of this operation. All ordering modes are possible. Note
2191 /// that using [`Acquire`] makes the store part of this operation
2192 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2193 ///
2194 /// **Note**: This method is only available on platforms that support atomic
2195 /// operations on [`AtomicPtr`].
2196 ///
2197 /// [`wrapping_add`]: pointer::wrapping_add
2198 ///
2199 /// # Examples
2200 ///
2201 /// ```
2202 /// #![feature(strict_provenance_atomic_ptr)]
2203 /// use core::sync::atomic::{AtomicPtr, Ordering};
2204 ///
2205 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2206 /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0);
2207 /// // Note: units of `size_of::<i64>()`.
2208 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8);
2209 /// ```
2210 #[inline]
2211 #[cfg(target_has_atomic = "ptr")]
2212 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
2213 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2214 pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T {
2215 self.fetch_byte_add(val.wrapping_mul(size_of::<T>()), order)
2216 }
2217
2218 /// Offsets the pointer's address by subtracting `val` (in units of `T`),
2219 /// returning the previous pointer.
2220 ///
2221 /// This is equivalent to using [`wrapping_sub`] to atomically perform the
2222 /// equivalent of `ptr = ptr.wrapping_sub(val);`.
2223 ///
2224 /// This method operates in units of `T`, which means that it cannot be used
2225 /// to offset the pointer by an amount which is not a multiple of
2226 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2227 /// work with a deliberately misaligned pointer. In such cases, you may use
2228 /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead.
2229 ///
2230 /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory
2231 /// ordering of this operation. All ordering modes are possible. Note that
2232 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2233 /// and using [`Release`] makes the load part [`Relaxed`].
2234 ///
2235 /// **Note**: This method is only available on platforms that support atomic
2236 /// operations on [`AtomicPtr`].
2237 ///
2238 /// [`wrapping_sub`]: pointer::wrapping_sub
2239 ///
2240 /// # Examples
2241 ///
2242 /// ```
2243 /// #![feature(strict_provenance_atomic_ptr)]
2244 /// use core::sync::atomic::{AtomicPtr, Ordering};
2245 ///
2246 /// let array = [1i32, 2i32];
2247 /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _);
2248 ///
2249 /// assert!(core::ptr::eq(
2250 /// atom.fetch_ptr_sub(1, Ordering::Relaxed),
2251 /// &array[1],
2252 /// ));
2253 /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0]));
2254 /// ```
2255 #[inline]
2256 #[cfg(target_has_atomic = "ptr")]
2257 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
2258 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2259 pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T {
2260 self.fetch_byte_sub(val.wrapping_mul(size_of::<T>()), order)
2261 }
2262
2263 /// Offsets the pointer's address by adding `val` *bytes*, returning the
2264 /// previous pointer.
2265 ///
2266 /// This is equivalent to using [`wrapping_byte_add`] to atomically
2267 /// perform `ptr = ptr.wrapping_byte_add(val)`.
2268 ///
2269 /// `fetch_byte_add` takes an [`Ordering`] argument which describes the
2270 /// memory ordering of this operation. All ordering modes are possible. Note
2271 /// that using [`Acquire`] makes the store part of this operation
2272 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2273 ///
2274 /// **Note**: This method is only available on platforms that support atomic
2275 /// operations on [`AtomicPtr`].
2276 ///
2277 /// [`wrapping_byte_add`]: pointer::wrapping_byte_add
2278 ///
2279 /// # Examples
2280 ///
2281 /// ```
2282 /// #![feature(strict_provenance_atomic_ptr)]
2283 /// use core::sync::atomic::{AtomicPtr, Ordering};
2284 ///
2285 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2286 /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0);
2287 /// // Note: in units of bytes, not `size_of::<i64>()`.
2288 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1);
2289 /// ```
2290 #[inline]
2291 #[cfg(target_has_atomic = "ptr")]
2292 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
2293 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2294 pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T {
2295 // SAFETY: data races are prevented by atomic intrinsics.
2296 unsafe { atomic_add(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() }
2297 }
2298
2299 /// Offsets the pointer's address by subtracting `val` *bytes*, returning the
2300 /// previous pointer.
2301 ///
2302 /// This is equivalent to using [`wrapping_byte_sub`] to atomically
2303 /// perform `ptr = ptr.wrapping_byte_sub(val)`.
2304 ///
2305 /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the
2306 /// memory ordering of this operation. All ordering modes are possible. Note
2307 /// that using [`Acquire`] makes the store part of this operation
2308 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2309 ///
2310 /// **Note**: This method is only available on platforms that support atomic
2311 /// operations on [`AtomicPtr`].
2312 ///
2313 /// [`wrapping_byte_sub`]: pointer::wrapping_byte_sub
2314 ///
2315 /// # Examples
2316 ///
2317 /// ```
2318 /// #![feature(strict_provenance_atomic_ptr)]
2319 /// use core::sync::atomic::{AtomicPtr, Ordering};
2320 ///
2321 /// let atom = AtomicPtr::<i64>::new(core::ptr::without_provenance_mut(1));
2322 /// assert_eq!(atom.fetch_byte_sub(1, Ordering::Relaxed).addr(), 1);
2323 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 0);
2324 /// ```
2325 #[inline]
2326 #[cfg(target_has_atomic = "ptr")]
2327 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
2328 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2329 pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T {
2330 // SAFETY: data races are prevented by atomic intrinsics.
2331 unsafe { atomic_sub(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() }
2332 }
2333
2334 /// Performs a bitwise "or" operation on the address of the current pointer,
2335 /// and the argument `val`, and stores a pointer with provenance of the
2336 /// current pointer and the resulting address.
2337 ///
2338 /// This is equivalent to using [`map_addr`] to atomically perform
2339 /// `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged
2340 /// pointer schemes to atomically set tag bits.
2341 ///
2342 /// **Caveat**: This operation returns the previous value. To compute the
2343 /// stored value without losing provenance, you may use [`map_addr`]. For
2344 /// example: `a.fetch_or(val).map_addr(|a| a | val)`.
2345 ///
2346 /// `fetch_or` takes an [`Ordering`] argument which describes the memory
2347 /// ordering of this operation. All ordering modes are possible. Note that
2348 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2349 /// and using [`Release`] makes the load part [`Relaxed`].
2350 ///
2351 /// **Note**: This method is only available on platforms that support atomic
2352 /// operations on [`AtomicPtr`].
2353 ///
2354 /// This API and its claimed semantics are part of the Strict Provenance
2355 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2356 /// details.
2357 ///
2358 /// [`map_addr`]: pointer::map_addr
2359 ///
2360 /// # Examples
2361 ///
2362 /// ```
2363 /// #![feature(strict_provenance_atomic_ptr)]
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 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
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(), core::ptr::without_provenance_mut(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 /// #![feature(strict_provenance_atomic_ptr)]
2415 /// use core::sync::atomic::{AtomicPtr, Ordering};
2416 ///
2417 /// let pointer = &mut 3i64 as *mut i64;
2418 /// // A tagged pointer
2419 /// let atom = AtomicPtr::<i64>::new(pointer.map_addr(|a| a | 1));
2420 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1);
2421 /// // Untag, and extract the previously tagged pointer.
2422 /// let untagged = atom.fetch_and(!1, Ordering::Relaxed)
2423 /// .map_addr(|a| a & !1);
2424 /// assert_eq!(untagged, pointer);
2425 /// ```
2426 #[inline]
2427 #[cfg(target_has_atomic = "ptr")]
2428 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
2429 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2430 pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T {
2431 // SAFETY: data races are prevented by atomic intrinsics.
2432 unsafe { atomic_and(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() }
2433 }
2434
2435 /// Performs a bitwise "xor" operation on the address of the current
2436 /// pointer, and the argument `val`, and stores a pointer with provenance of
2437 /// the current pointer and the resulting address.
2438 ///
2439 /// This is equivalent to using [`map_addr`] to atomically perform
2440 /// `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged
2441 /// pointer schemes to atomically toggle tag bits.
2442 ///
2443 /// **Caveat**: This operation returns the previous value. To compute the
2444 /// stored value without losing provenance, you may use [`map_addr`]. For
2445 /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`.
2446 ///
2447 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory
2448 /// ordering of this operation. All ordering modes are possible. Note that
2449 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2450 /// and using [`Release`] makes the load part [`Relaxed`].
2451 ///
2452 /// **Note**: This method is only available on platforms that support atomic
2453 /// operations on [`AtomicPtr`].
2454 ///
2455 /// This API and its claimed semantics are part of the Strict Provenance
2456 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2457 /// details.
2458 ///
2459 /// [`map_addr`]: pointer::map_addr
2460 ///
2461 /// # Examples
2462 ///
2463 /// ```
2464 /// #![feature(strict_provenance_atomic_ptr)]
2465 /// use core::sync::atomic::{AtomicPtr, Ordering};
2466 ///
2467 /// let pointer = &mut 3i64 as *mut i64;
2468 /// let atom = AtomicPtr::<i64>::new(pointer);
2469 ///
2470 /// // Toggle a tag bit on the pointer.
2471 /// atom.fetch_xor(1, Ordering::Relaxed);
2472 /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1);
2473 /// ```
2474 #[inline]
2475 #[cfg(target_has_atomic = "ptr")]
2476 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
2477 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2478 pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T {
2479 // SAFETY: data races are prevented by atomic intrinsics.
2480 unsafe { atomic_xor(self.p.get(), core::ptr::without_provenance_mut(val), order).cast() }
2481 }
2482
2483 /// Returns a mutable pointer to the underlying pointer.
2484 ///
2485 /// Doing non-atomic reads and writes on the resulting pointer can be a data race.
2486 /// This method is mostly useful for FFI, where the function signature may use
2487 /// `*mut *mut T` instead of `&AtomicPtr<T>`.
2488 ///
2489 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
2490 /// atomic types work with interior mutability. All modifications of an atomic change the value
2491 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
2492 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
2493 /// requirements of the [memory model].
2494 ///
2495 /// # Examples
2496 ///
2497 /// ```ignore (extern-declaration)
2498 /// use std::sync::atomic::AtomicPtr;
2499 ///
2500 /// extern "C" {
2501 /// fn my_atomic_op(arg: *mut *mut u32);
2502 /// }
2503 ///
2504 /// let mut value = 17;
2505 /// let atomic = AtomicPtr::new(&mut value);
2506 ///
2507 /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
2508 /// unsafe {
2509 /// my_atomic_op(atomic.as_ptr());
2510 /// }
2511 /// ```
2512 ///
2513 /// [memory model]: self#memory-model-for-atomic-accesses
2514 #[inline]
2515 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
2516 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
2517 #[rustc_never_returns_null_ptr]
2518 pub const fn as_ptr(&self) -> *mut *mut T {
2519 self.p.get()
2520 }
2521}
2522
2523#[cfg(target_has_atomic_load_store = "8")]
2524#[stable(feature = "atomic_bool_from", since = "1.24.0")]
2525#[rustc_const_unstable(feature = "const_try", issue = "74935")]
2526impl const From<bool> for AtomicBool {
2527 /// Converts a `bool` into an `AtomicBool`.
2528 ///
2529 /// # Examples
2530 ///
2531 /// ```
2532 /// use std::sync::atomic::AtomicBool;
2533 /// let atomic_bool = AtomicBool::from(true);
2534 /// assert_eq!(format!("{atomic_bool:?}"), "true")
2535 /// ```
2536 #[inline]
2537 fn from(b: bool) -> Self {
2538 Self::new(b)
2539 }
2540}
2541
2542#[cfg(target_has_atomic_load_store = "ptr")]
2543#[stable(feature = "atomic_from", since = "1.23.0")]
2544impl<T> From<*mut T> for AtomicPtr<T> {
2545 /// Converts a `*mut T` into an `AtomicPtr<T>`.
2546 #[inline]
2547 fn from(p: *mut T) -> Self {
2548 Self::new(p)
2549 }
2550}
2551
2552#[allow(unused_macros)] // This macro ends up being unused on some architectures.
2553macro_rules! if_8_bit {
2554 (u8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2555 (i8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2556 ($_:ident, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($no)*)?) };
2557}
2558
2559#[cfg(target_has_atomic_load_store)]
2560macro_rules! atomic_int {
2561 ($cfg_cas:meta,
2562 $cfg_align:meta,
2563 $stable:meta,
2564 $stable_cxchg:meta,
2565 $stable_debug:meta,
2566 $stable_access:meta,
2567 $stable_from:meta,
2568 $stable_nand:meta,
2569 $const_stable_new:meta,
2570 $const_stable_into_inner:meta,
2571 $diagnostic_item:meta,
2572 $s_int_type:literal,
2573 $extra_feature:expr,
2574 $min_fn:ident, $max_fn:ident,
2575 $align:expr,
2576 $int_type:ident $atomic_type:ident) => {
2577 /// An integer type which can be safely shared between threads.
2578 ///
2579 /// This type has the same
2580 #[doc = if_8_bit!(
2581 $int_type,
2582 yes = ["size, alignment, and bit validity"],
2583 no = ["size and bit validity"],
2584 )]
2585 /// as the underlying integer type, [`
2586 #[doc = $s_int_type]
2587 /// `].
2588 #[doc = if_8_bit! {
2589 $int_type,
2590 no = [
2591 "However, the alignment of this type is always equal to its ",
2592 "size, even on targets where [`", $s_int_type, "`] has a ",
2593 "lesser alignment."
2594 ],
2595 }]
2596 ///
2597 /// For more about the differences between atomic types and
2598 /// non-atomic types as well as information about the portability of
2599 /// this type, please see the [module-level documentation].
2600 ///
2601 /// **Note:** This type is only available on platforms that support
2602 /// atomic loads and stores of [`
2603 #[doc = $s_int_type]
2604 /// `].
2605 ///
2606 /// [module-level documentation]: crate::sync::atomic
2607 #[$stable]
2608 #[$diagnostic_item]
2609 #[repr(C, align($align))]
2610 pub struct $atomic_type {
2611 v: UnsafeCell<$int_type>,
2612 }
2613
2614 #[$stable]
2615 impl Default for $atomic_type {
2616 #[inline]
2617 fn default() -> Self {
2618 Self::new(Default::default())
2619 }
2620 }
2621
2622 #[$stable_from]
2623 #[rustc_const_unstable(feature = "const_try", issue = "74935")]
2624 impl const From<$int_type> for $atomic_type {
2625 #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")]
2626 #[inline]
2627 fn from(v: $int_type) -> Self { Self::new(v) }
2628 }
2629
2630 #[$stable_debug]
2631 impl fmt::Debug for $atomic_type {
2632 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2633 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
2634 }
2635 }
2636
2637 // Send is implicitly implemented.
2638 #[$stable]
2639 unsafe impl Sync for $atomic_type {}
2640
2641 impl $atomic_type {
2642 /// Creates a new atomic integer.
2643 ///
2644 /// # Examples
2645 ///
2646 /// ```
2647 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2648 ///
2649 #[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")]
2650 /// ```
2651 #[inline]
2652 #[$stable]
2653 #[$const_stable_new]
2654 #[must_use]
2655 pub const fn new(v: $int_type) -> Self {
2656 Self {v: UnsafeCell::new(v)}
2657 }
2658
2659 /// Creates a new reference to an atomic integer from a pointer.
2660 ///
2661 /// # Examples
2662 ///
2663 /// ```
2664 #[doc = concat!($extra_feature, "use std::sync::atomic::{self, ", stringify!($atomic_type), "};")]
2665 ///
2666 /// // Get a pointer to an allocated value
2667 #[doc = concat!("let ptr: *mut ", stringify!($int_type), " = Box::into_raw(Box::new(0));")]
2668 ///
2669 #[doc = concat!("assert!(ptr.cast::<", stringify!($atomic_type), ">().is_aligned());")]
2670 ///
2671 /// {
2672 /// // Create an atomic view of the allocated value
2673 // SAFETY: this is a doc comment, tidy, it can't hurt you (also guaranteed by the construction of `ptr` and the assert above)
2674 #[doc = concat!(" let atomic = unsafe {", stringify!($atomic_type), "::from_ptr(ptr) };")]
2675 ///
2676 /// // Use `atomic` for atomic operations, possibly share it with other threads
2677 /// atomic.store(1, atomic::Ordering::Relaxed);
2678 /// }
2679 ///
2680 /// // It's ok to non-atomically access the value behind `ptr`,
2681 /// // since the reference to the atomic ended its lifetime in the block above
2682 /// assert_eq!(unsafe { *ptr }, 1);
2683 ///
2684 /// // Deallocate the value
2685 /// unsafe { drop(Box::from_raw(ptr)) }
2686 /// ```
2687 ///
2688 /// # Safety
2689 ///
2690 /// * `ptr` must be aligned to
2691 #[doc = concat!(" `align_of::<", stringify!($atomic_type), ">()`")]
2692 #[doc = if_8_bit!{
2693 $int_type,
2694 yes = [
2695 " (note that this is always true, since `align_of::<",
2696 stringify!($atomic_type), ">() == 1`)."
2697 ],
2698 no = [
2699 " (note that on some platforms this can be bigger than `align_of::<",
2700 stringify!($int_type), ">()`)."
2701 ],
2702 }]
2703 /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
2704 /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
2705 /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
2706 /// sizes, without synchronization.
2707 ///
2708 /// [valid]: crate::ptr#safety
2709 /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
2710 #[inline]
2711 #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
2712 #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
2713 pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type {
2714 // SAFETY: guaranteed by the caller
2715 unsafe { &*ptr.cast() }
2716 }
2717
2718
2719 /// Returns a mutable reference to the underlying integer.
2720 ///
2721 /// This is safe because the mutable reference guarantees that no other threads are
2722 /// concurrently accessing the atomic data.
2723 ///
2724 /// # Examples
2725 ///
2726 /// ```
2727 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2728 ///
2729 #[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")]
2730 /// assert_eq!(*some_var.get_mut(), 10);
2731 /// *some_var.get_mut() = 5;
2732 /// assert_eq!(some_var.load(Ordering::SeqCst), 5);
2733 /// ```
2734 #[inline]
2735 #[$stable_access]
2736 pub fn get_mut(&mut self) -> &mut $int_type {
2737 self.v.get_mut()
2738 }
2739
2740 #[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")]
2741 ///
2742 #[doc = if_8_bit! {
2743 $int_type,
2744 no = [
2745 "**Note:** This function is only available on targets where `",
2746 stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
2747 ],
2748 }]
2749 ///
2750 /// # Examples
2751 ///
2752 /// ```
2753 /// #![feature(atomic_from_mut)]
2754 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2755 ///
2756 /// let mut some_int = 123;
2757 #[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")]
2758 /// a.store(100, Ordering::Relaxed);
2759 /// assert_eq!(some_int, 100);
2760 /// ```
2761 ///
2762 #[inline]
2763 #[$cfg_align]
2764 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2765 pub fn from_mut(v: &mut $int_type) -> &mut Self {
2766 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2767 // SAFETY:
2768 // - the mutable reference guarantees unique ownership.
2769 // - the alignment of `$int_type` and `Self` is the
2770 // same, as promised by $cfg_align and verified above.
2771 unsafe { &mut *(v as *mut $int_type as *mut Self) }
2772 }
2773
2774 #[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")]
2775 ///
2776 /// This is safe because the mutable reference guarantees that no other threads are
2777 /// concurrently accessing the atomic data.
2778 ///
2779 /// # Examples
2780 ///
2781 /// ```ignore-wasm
2782 /// #![feature(atomic_from_mut)]
2783 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2784 ///
2785 #[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")]
2786 ///
2787 #[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")]
2788 /// assert_eq!(view, [0; 10]);
2789 /// view
2790 /// .iter_mut()
2791 /// .enumerate()
2792 /// .for_each(|(idx, int)| *int = idx as _);
2793 ///
2794 /// std::thread::scope(|s| {
2795 /// some_ints
2796 /// .iter()
2797 /// .enumerate()
2798 /// .for_each(|(idx, int)| {
2799 /// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
2800 /// })
2801 /// });
2802 /// ```
2803 #[inline]
2804 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2805 pub fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] {
2806 // SAFETY: the mutable reference guarantees unique ownership.
2807 unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) }
2808 }
2809
2810 #[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")]
2811 ///
2812 /// # Examples
2813 ///
2814 /// ```ignore-wasm
2815 /// #![feature(atomic_from_mut)]
2816 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2817 ///
2818 /// let mut some_ints = [0; 10];
2819 #[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")]
2820 /// std::thread::scope(|s| {
2821 /// for i in 0..a.len() {
2822 /// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
2823 /// }
2824 /// });
2825 /// for (i, n) in some_ints.into_iter().enumerate() {
2826 /// assert_eq!(i, n as usize);
2827 /// }
2828 /// ```
2829 #[inline]
2830 #[$cfg_align]
2831 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2832 pub fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] {
2833 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2834 // SAFETY:
2835 // - the mutable reference guarantees unique ownership.
2836 // - the alignment of `$int_type` and `Self` is the
2837 // same, as promised by $cfg_align and verified above.
2838 unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) }
2839 }
2840
2841 /// Consumes the atomic and returns the contained value.
2842 ///
2843 /// This is safe because passing `self` by value guarantees that no other threads are
2844 /// concurrently accessing the atomic data.
2845 ///
2846 /// # Examples
2847 ///
2848 /// ```
2849 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2850 ///
2851 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2852 /// assert_eq!(some_var.into_inner(), 5);
2853 /// ```
2854 #[inline]
2855 #[$stable_access]
2856 #[$const_stable_into_inner]
2857 pub const fn into_inner(self) -> $int_type {
2858 self.v.into_inner()
2859 }
2860
2861 /// Loads a value from the atomic integer.
2862 ///
2863 /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2864 /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
2865 ///
2866 /// # Panics
2867 ///
2868 /// Panics if `order` is [`Release`] or [`AcqRel`].
2869 ///
2870 /// # Examples
2871 ///
2872 /// ```
2873 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2874 ///
2875 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2876 ///
2877 /// assert_eq!(some_var.load(Ordering::Relaxed), 5);
2878 /// ```
2879 #[inline]
2880 #[$stable]
2881 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2882 pub fn load(&self, order: Ordering) -> $int_type {
2883 // SAFETY: data races are prevented by atomic intrinsics.
2884 unsafe { atomic_load(self.v.get(), order) }
2885 }
2886
2887 /// Stores a value into the atomic integer.
2888 ///
2889 /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2890 /// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
2891 ///
2892 /// # Panics
2893 ///
2894 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
2895 ///
2896 /// # Examples
2897 ///
2898 /// ```
2899 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2900 ///
2901 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2902 ///
2903 /// some_var.store(10, Ordering::Relaxed);
2904 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2905 /// ```
2906 #[inline]
2907 #[$stable]
2908 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2909 pub fn store(&self, val: $int_type, order: Ordering) {
2910 // SAFETY: data races are prevented by atomic intrinsics.
2911 unsafe { atomic_store(self.v.get(), val, order); }
2912 }
2913
2914 /// Stores a value into the atomic integer, returning the previous value.
2915 ///
2916 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
2917 /// of this operation. All ordering modes are possible. Note that using
2918 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2919 /// using [`Release`] makes the load part [`Relaxed`].
2920 ///
2921 /// **Note**: This method is only available on platforms that support atomic operations on
2922 #[doc = concat!("[`", $s_int_type, "`].")]
2923 ///
2924 /// # Examples
2925 ///
2926 /// ```
2927 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2928 ///
2929 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2930 ///
2931 /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
2932 /// ```
2933 #[inline]
2934 #[$stable]
2935 #[$cfg_cas]
2936 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2937 pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
2938 // SAFETY: data races are prevented by atomic intrinsics.
2939 unsafe { atomic_swap(self.v.get(), val, order) }
2940 }
2941
2942 /// Stores a value into the atomic integer if the current value is the same as
2943 /// the `current` value.
2944 ///
2945 /// The return value is always the previous value. If it is equal to `current`, then the
2946 /// value was updated.
2947 ///
2948 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
2949 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
2950 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
2951 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
2952 /// happens, and using [`Release`] makes the load part [`Relaxed`].
2953 ///
2954 /// **Note**: This method is only available on platforms that support atomic operations on
2955 #[doc = concat!("[`", $s_int_type, "`].")]
2956 ///
2957 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
2958 ///
2959 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
2960 /// memory orderings:
2961 ///
2962 /// Original | Success | Failure
2963 /// -------- | ------- | -------
2964 /// Relaxed | Relaxed | Relaxed
2965 /// Acquire | Acquire | Acquire
2966 /// Release | Release | Relaxed
2967 /// AcqRel | AcqRel | Acquire
2968 /// SeqCst | SeqCst | SeqCst
2969 ///
2970 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
2971 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
2972 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
2973 /// rather than to infer success vs failure based on the value that was read.
2974 ///
2975 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
2976 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
2977 /// which allows the compiler to generate better assembly code when the compare and swap
2978 /// is used in a loop.
2979 ///
2980 /// # Examples
2981 ///
2982 /// ```
2983 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2984 ///
2985 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2986 ///
2987 /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
2988 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2989 ///
2990 /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
2991 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2992 /// ```
2993 #[inline]
2994 #[$stable]
2995 #[deprecated(
2996 since = "1.50.0",
2997 note = "Use `compare_exchange` or `compare_exchange_weak` instead")
2998 ]
2999 #[$cfg_cas]
3000 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3001 pub fn compare_and_swap(&self,
3002 current: $int_type,
3003 new: $int_type,
3004 order: Ordering) -> $int_type {
3005 match self.compare_exchange(current,
3006 new,
3007 order,
3008 strongest_failure_ordering(order)) {
3009 Ok(x) => x,
3010 Err(x) => x,
3011 }
3012 }
3013
3014 /// Stores a value into the atomic integer if the current value is the same as
3015 /// the `current` value.
3016 ///
3017 /// The return value is a result indicating whether the new value was written and
3018 /// containing the previous value. On success this value is guaranteed to be equal to
3019 /// `current`.
3020 ///
3021 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
3022 /// ordering of this operation. `success` describes the required ordering for the
3023 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3024 /// `failure` describes the required ordering for the load operation that takes place when
3025 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3026 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3027 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3028 ///
3029 /// **Note**: This method is only available on platforms that support atomic operations on
3030 #[doc = concat!("[`", $s_int_type, "`].")]
3031 ///
3032 /// # Examples
3033 ///
3034 /// ```
3035 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3036 ///
3037 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
3038 ///
3039 /// assert_eq!(some_var.compare_exchange(5, 10,
3040 /// Ordering::Acquire,
3041 /// Ordering::Relaxed),
3042 /// Ok(5));
3043 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3044 ///
3045 /// assert_eq!(some_var.compare_exchange(6, 12,
3046 /// Ordering::SeqCst,
3047 /// Ordering::Acquire),
3048 /// Err(10));
3049 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3050 /// ```
3051 ///
3052 /// # Considerations
3053 ///
3054 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3055 /// of CAS operations. In particular, a load of the value followed by a successful
3056 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3057 /// changed the value in the interim! This is usually important when the *equality* check in
3058 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3059 /// does not necessarily imply identity. This is a particularly common case for pointers, as
3060 /// a pointer holding the same address does not imply that the same object exists at that
3061 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3062 ///
3063 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3064 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3065 #[inline]
3066 #[$stable_cxchg]
3067 #[$cfg_cas]
3068 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3069 pub fn compare_exchange(&self,
3070 current: $int_type,
3071 new: $int_type,
3072 success: Ordering,
3073 failure: Ordering) -> Result<$int_type, $int_type> {
3074 // SAFETY: data races are prevented by atomic intrinsics.
3075 unsafe { atomic_compare_exchange(self.v.get(), current, new, success, failure) }
3076 }
3077
3078 /// Stores a value into the atomic integer if the current value is the same as
3079 /// the `current` value.
3080 ///
3081 #[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")]
3082 /// this function is allowed to spuriously fail even
3083 /// when the comparison succeeds, which can result in more efficient code on some
3084 /// platforms. The return value is a result indicating whether the new value was
3085 /// written and containing the previous value.
3086 ///
3087 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
3088 /// ordering of this operation. `success` describes the required ordering for the
3089 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3090 /// `failure` describes the required ordering for the load operation that takes place when
3091 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3092 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3093 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3094 ///
3095 /// **Note**: This method is only available on platforms that support atomic operations on
3096 #[doc = concat!("[`", $s_int_type, "`].")]
3097 ///
3098 /// # Examples
3099 ///
3100 /// ```
3101 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3102 ///
3103 #[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")]
3104 ///
3105 /// let mut old = val.load(Ordering::Relaxed);
3106 /// loop {
3107 /// let new = old * 2;
3108 /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
3109 /// Ok(_) => break,
3110 /// Err(x) => old = x,
3111 /// }
3112 /// }
3113 /// ```
3114 ///
3115 /// # Considerations
3116 ///
3117 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3118 /// of CAS operations. In particular, a load of the value followed by a successful
3119 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3120 /// changed the value in the interim. This is usually important when the *equality* check in
3121 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3122 /// does not necessarily imply identity. This is a particularly common case for pointers, as
3123 /// a pointer holding the same address does not imply that the same object exists at that
3124 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3125 ///
3126 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3127 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3128 #[inline]
3129 #[$stable_cxchg]
3130 #[$cfg_cas]
3131 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3132 pub fn compare_exchange_weak(&self,
3133 current: $int_type,
3134 new: $int_type,
3135 success: Ordering,
3136 failure: Ordering) -> Result<$int_type, $int_type> {
3137 // SAFETY: data races are prevented by atomic intrinsics.
3138 unsafe {
3139 atomic_compare_exchange_weak(self.v.get(), current, new, success, failure)
3140 }
3141 }
3142
3143 /// Adds to the current value, returning the previous value.
3144 ///
3145 /// This operation wraps around on overflow.
3146 ///
3147 /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
3148 /// of this operation. All ordering modes are possible. Note that using
3149 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3150 /// using [`Release`] makes the load part [`Relaxed`].
3151 ///
3152 /// **Note**: This method is only available on platforms that support atomic operations on
3153 #[doc = concat!("[`", $s_int_type, "`].")]
3154 ///
3155 /// # Examples
3156 ///
3157 /// ```
3158 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3159 ///
3160 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")]
3161 /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
3162 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3163 /// ```
3164 #[inline]
3165 #[$stable]
3166 #[$cfg_cas]
3167 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3168 pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
3169 // SAFETY: data races are prevented by atomic intrinsics.
3170 unsafe { atomic_add(self.v.get(), val, order) }
3171 }
3172
3173 /// Subtracts from the current value, returning the previous value.
3174 ///
3175 /// This operation wraps around on overflow.
3176 ///
3177 /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
3178 /// of this operation. All ordering modes are possible. Note that using
3179 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3180 /// using [`Release`] makes the load part [`Relaxed`].
3181 ///
3182 /// **Note**: This method is only available on platforms that support atomic operations on
3183 #[doc = concat!("[`", $s_int_type, "`].")]
3184 ///
3185 /// # Examples
3186 ///
3187 /// ```
3188 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3189 ///
3190 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")]
3191 /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
3192 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3193 /// ```
3194 #[inline]
3195 #[$stable]
3196 #[$cfg_cas]
3197 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3198 pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
3199 // SAFETY: data races are prevented by atomic intrinsics.
3200 unsafe { atomic_sub(self.v.get(), val, order) }
3201 }
3202
3203 /// Bitwise "and" with the current value.
3204 ///
3205 /// Performs a bitwise "and" operation on the current value and the argument `val`, and
3206 /// sets the new value to the result.
3207 ///
3208 /// Returns the previous value.
3209 ///
3210 /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
3211 /// of this operation. All ordering modes are possible. Note that using
3212 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3213 /// using [`Release`] makes the load part [`Relaxed`].
3214 ///
3215 /// **Note**: This method is only available on platforms that support atomic operations on
3216 #[doc = concat!("[`", $s_int_type, "`].")]
3217 ///
3218 /// # Examples
3219 ///
3220 /// ```
3221 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3222 ///
3223 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3224 /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
3225 /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
3226 /// ```
3227 #[inline]
3228 #[$stable]
3229 #[$cfg_cas]
3230 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3231 pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
3232 // SAFETY: data races are prevented by atomic intrinsics.
3233 unsafe { atomic_and(self.v.get(), val, order) }
3234 }
3235
3236 /// Bitwise "nand" with the current value.
3237 ///
3238 /// Performs a bitwise "nand" operation on the current value and the argument `val`, and
3239 /// sets the new value to the result.
3240 ///
3241 /// Returns the previous value.
3242 ///
3243 /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
3244 /// of this operation. All ordering modes are possible. Note that using
3245 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3246 /// using [`Release`] makes the load part [`Relaxed`].
3247 ///
3248 /// **Note**: This method is only available on platforms that support atomic operations on
3249 #[doc = concat!("[`", $s_int_type, "`].")]
3250 ///
3251 /// # Examples
3252 ///
3253 /// ```
3254 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3255 ///
3256 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")]
3257 /// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
3258 /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
3259 /// ```
3260 #[inline]
3261 #[$stable_nand]
3262 #[$cfg_cas]
3263 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3264 pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
3265 // SAFETY: data races are prevented by atomic intrinsics.
3266 unsafe { atomic_nand(self.v.get(), val, order) }
3267 }
3268
3269 /// Bitwise "or" with the current value.
3270 ///
3271 /// Performs a bitwise "or" operation on the current value and the argument `val`, and
3272 /// sets the new value to the result.
3273 ///
3274 /// Returns the previous value.
3275 ///
3276 /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
3277 /// of this operation. All ordering modes are possible. Note that using
3278 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3279 /// using [`Release`] makes the load part [`Relaxed`].
3280 ///
3281 /// **Note**: This method is only available on platforms that support atomic operations on
3282 #[doc = concat!("[`", $s_int_type, "`].")]
3283 ///
3284 /// # Examples
3285 ///
3286 /// ```
3287 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3288 ///
3289 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3290 /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
3291 /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
3292 /// ```
3293 #[inline]
3294 #[$stable]
3295 #[$cfg_cas]
3296 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3297 pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
3298 // SAFETY: data races are prevented by atomic intrinsics.
3299 unsafe { atomic_or(self.v.get(), val, order) }
3300 }
3301
3302 /// Bitwise "xor" with the current value.
3303 ///
3304 /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
3305 /// sets the new value to the result.
3306 ///
3307 /// Returns the previous value.
3308 ///
3309 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
3310 /// of this operation. All ordering modes are possible. Note that using
3311 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3312 /// using [`Release`] makes the load part [`Relaxed`].
3313 ///
3314 /// **Note**: This method is only available on platforms that support atomic operations on
3315 #[doc = concat!("[`", $s_int_type, "`].")]
3316 ///
3317 /// # Examples
3318 ///
3319 /// ```
3320 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3321 ///
3322 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3323 /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
3324 /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
3325 /// ```
3326 #[inline]
3327 #[$stable]
3328 #[$cfg_cas]
3329 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3330 pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
3331 // SAFETY: data races are prevented by atomic intrinsics.
3332 unsafe { atomic_xor(self.v.get(), val, order) }
3333 }
3334
3335 /// Fetches the value, and applies a function to it that returns an optional
3336 /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3337 /// `Err(previous_value)`.
3338 ///
3339 /// Note: This may call the function multiple times if the value has been changed from other threads in
3340 /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3341 /// only once to the stored value.
3342 ///
3343 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3344 /// The first describes the required ordering for when the operation finally succeeds while the second
3345 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3346 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3347 /// respectively.
3348 ///
3349 /// Using [`Acquire`] as success ordering makes the store part
3350 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3351 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3352 ///
3353 /// **Note**: This method is only available on platforms that support atomic operations on
3354 #[doc = concat!("[`", $s_int_type, "`].")]
3355 ///
3356 /// # Considerations
3357 ///
3358 /// This method is not magic; it is not provided by the hardware, and does not act like a
3359 /// critical section or mutex.
3360 ///
3361 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3362 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3363 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3364 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3365 ///
3366 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3367 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3368 ///
3369 /// # Examples
3370 ///
3371 /// ```rust
3372 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3373 ///
3374 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3375 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3376 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3377 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3378 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3379 /// ```
3380 #[inline]
3381 #[stable(feature = "no_more_cas", since = "1.45.0")]
3382 #[$cfg_cas]
3383 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3384 pub fn fetch_update<F>(&self,
3385 set_order: Ordering,
3386 fetch_order: Ordering,
3387 mut f: F) -> Result<$int_type, $int_type>
3388 where F: FnMut($int_type) -> Option<$int_type> {
3389 let mut prev = self.load(fetch_order);
3390 while let Some(next) = f(prev) {
3391 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
3392 x @ Ok(_) => return x,
3393 Err(next_prev) => prev = next_prev
3394 }
3395 }
3396 Err(prev)
3397 }
3398
3399 /// Fetches the value, and applies a function to it that returns an optional
3400 /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3401 /// `Err(previous_value)`.
3402 ///
3403 #[doc = concat!("See also: [`update`](`", stringify!($atomic_type), "::update`).")]
3404 ///
3405 /// Note: This may call the function multiple times if the value has been changed from other threads in
3406 /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3407 /// only once to the stored value.
3408 ///
3409 /// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3410 /// The first describes the required ordering for when the operation finally succeeds while the second
3411 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3412 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3413 /// respectively.
3414 ///
3415 /// Using [`Acquire`] as success ordering makes the store part
3416 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3417 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3418 ///
3419 /// **Note**: This method is only available on platforms that support atomic operations on
3420 #[doc = concat!("[`", $s_int_type, "`].")]
3421 ///
3422 /// # Considerations
3423 ///
3424 /// This method is not magic; it is not provided by the hardware, and does not act like a
3425 /// critical section or mutex.
3426 ///
3427 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3428 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3429 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3430 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3431 ///
3432 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3433 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3434 ///
3435 /// # Examples
3436 ///
3437 /// ```rust
3438 /// #![feature(atomic_try_update)]
3439 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3440 ///
3441 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3442 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3443 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3444 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3445 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3446 /// ```
3447 #[inline]
3448 #[unstable(feature = "atomic_try_update", issue = "135894")]
3449 #[$cfg_cas]
3450 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3451 pub fn try_update(
3452 &self,
3453 set_order: Ordering,
3454 fetch_order: Ordering,
3455 f: impl FnMut($int_type) -> Option<$int_type>,
3456 ) -> Result<$int_type, $int_type> {
3457 // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
3458 // when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
3459 self.fetch_update(set_order, fetch_order, f)
3460 }
3461
3462 /// Fetches the value, applies a function to it that it return a new value.
3463 /// The new value is stored and the old value is returned.
3464 ///
3465 #[doc = concat!("See also: [`try_update`](`", stringify!($atomic_type), "::try_update`).")]
3466 ///
3467 /// Note: This may call the function multiple times if the value has been changed from other threads in
3468 /// the meantime, but the function will have been applied only once to the stored value.
3469 ///
3470 /// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3471 /// The first describes the required ordering for when the operation finally succeeds while the second
3472 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3473 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3474 /// respectively.
3475 ///
3476 /// Using [`Acquire`] as success ordering makes the store part
3477 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3478 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3479 ///
3480 /// **Note**: This method is only available on platforms that support atomic operations on
3481 #[doc = concat!("[`", $s_int_type, "`].")]
3482 ///
3483 /// # Considerations
3484 ///
3485 /// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3486 /// This method is not magic; it is not provided by the hardware, and does not act like a
3487 /// critical section or mutex.
3488 ///
3489 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3490 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3491 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3492 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3493 ///
3494 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3495 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3496 ///
3497 /// # Examples
3498 ///
3499 /// ```rust
3500 /// #![feature(atomic_try_update)]
3501 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3502 ///
3503 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3504 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
3505 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
3506 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3507 /// ```
3508 #[inline]
3509 #[unstable(feature = "atomic_try_update", issue = "135894")]
3510 #[$cfg_cas]
3511 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3512 pub fn update(
3513 &self,
3514 set_order: Ordering,
3515 fetch_order: Ordering,
3516 mut f: impl FnMut($int_type) -> $int_type,
3517 ) -> $int_type {
3518 let mut prev = self.load(fetch_order);
3519 loop {
3520 match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
3521 Ok(x) => break x,
3522 Err(next_prev) => prev = next_prev,
3523 }
3524 }
3525 }
3526
3527 /// Maximum with the current value.
3528 ///
3529 /// Finds the maximum of the current value and the argument `val`, and
3530 /// sets the new value to the result.
3531 ///
3532 /// Returns the previous value.
3533 ///
3534 /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
3535 /// of this operation. All ordering modes are possible. Note that using
3536 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3537 /// using [`Release`] makes the load part [`Relaxed`].
3538 ///
3539 /// **Note**: This method is only available on platforms that support atomic operations on
3540 #[doc = concat!("[`", $s_int_type, "`].")]
3541 ///
3542 /// # Examples
3543 ///
3544 /// ```
3545 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3546 ///
3547 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3548 /// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
3549 /// assert_eq!(foo.load(Ordering::SeqCst), 42);
3550 /// ```
3551 ///
3552 /// If you want to obtain the maximum value in one step, you can use the following:
3553 ///
3554 /// ```
3555 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3556 ///
3557 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3558 /// let bar = 42;
3559 /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
3560 /// assert!(max_foo == 42);
3561 /// ```
3562 #[inline]
3563 #[stable(feature = "atomic_min_max", since = "1.45.0")]
3564 #[$cfg_cas]
3565 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3566 pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
3567 // SAFETY: data races are prevented by atomic intrinsics.
3568 unsafe { $max_fn(self.v.get(), val, order) }
3569 }
3570
3571 /// Minimum with the current value.
3572 ///
3573 /// Finds the minimum of the current value and the argument `val`, and
3574 /// sets the new value to the result.
3575 ///
3576 /// Returns the previous value.
3577 ///
3578 /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
3579 /// of this operation. All ordering modes are possible. Note that using
3580 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3581 /// using [`Release`] makes the load part [`Relaxed`].
3582 ///
3583 /// **Note**: This method is only available on platforms that support atomic operations on
3584 #[doc = concat!("[`", $s_int_type, "`].")]
3585 ///
3586 /// # Examples
3587 ///
3588 /// ```
3589 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3590 ///
3591 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3592 /// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
3593 /// assert_eq!(foo.load(Ordering::Relaxed), 23);
3594 /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
3595 /// assert_eq!(foo.load(Ordering::Relaxed), 22);
3596 /// ```
3597 ///
3598 /// If you want to obtain the minimum value in one step, you can use the following:
3599 ///
3600 /// ```
3601 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3602 ///
3603 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3604 /// let bar = 12;
3605 /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
3606 /// assert_eq!(min_foo, 12);
3607 /// ```
3608 #[inline]
3609 #[stable(feature = "atomic_min_max", since = "1.45.0")]
3610 #[$cfg_cas]
3611 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3612 pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
3613 // SAFETY: data races are prevented by atomic intrinsics.
3614 unsafe { $min_fn(self.v.get(), val, order) }
3615 }
3616
3617 /// Returns a mutable pointer to the underlying integer.
3618 ///
3619 /// Doing non-atomic reads and writes on the resulting integer can be a data race.
3620 /// This method is mostly useful for FFI, where the function signature may use
3621 #[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")]
3622 ///
3623 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
3624 /// atomic types work with interior mutability. All modifications of an atomic change the value
3625 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
3626 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
3627 /// requirements of the [memory model].
3628 ///
3629 /// # Examples
3630 ///
3631 /// ```ignore (extern-declaration)
3632 /// # fn main() {
3633 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
3634 ///
3635 /// extern "C" {
3636 #[doc = concat!(" fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")]
3637 /// }
3638 ///
3639 #[doc = concat!("let atomic = ", stringify!($atomic_type), "::new(1);")]
3640 ///
3641 /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
3642 /// unsafe {
3643 /// my_atomic_op(atomic.as_ptr());
3644 /// }
3645 /// # }
3646 /// ```
3647 ///
3648 /// [memory model]: self#memory-model-for-atomic-accesses
3649 #[inline]
3650 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
3651 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
3652 #[rustc_never_returns_null_ptr]
3653 pub const fn as_ptr(&self) -> *mut $int_type {
3654 self.v.get()
3655 }
3656 }
3657 }
3658}
3659
3660#[cfg(target_has_atomic_load_store = "8")]
3661atomic_int! {
3662 cfg(target_has_atomic = "8"),
3663 cfg(target_has_atomic_equal_alignment = "8"),
3664 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3665 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3666 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3667 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3668 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3669 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3670 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3671 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3672 rustc_diagnostic_item = "AtomicI8",
3673 "i8",
3674 "",
3675 atomic_min, atomic_max,
3676 1,
3677 i8 AtomicI8
3678}
3679#[cfg(target_has_atomic_load_store = "8")]
3680atomic_int! {
3681 cfg(target_has_atomic = "8"),
3682 cfg(target_has_atomic_equal_alignment = "8"),
3683 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3684 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3685 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3686 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3687 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3688 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3689 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3690 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3691 rustc_diagnostic_item = "AtomicU8",
3692 "u8",
3693 "",
3694 atomic_umin, atomic_umax,
3695 1,
3696 u8 AtomicU8
3697}
3698#[cfg(target_has_atomic_load_store = "16")]
3699atomic_int! {
3700 cfg(target_has_atomic = "16"),
3701 cfg(target_has_atomic_equal_alignment = "16"),
3702 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3703 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3704 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3705 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3706 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3707 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3708 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3709 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3710 rustc_diagnostic_item = "AtomicI16",
3711 "i16",
3712 "",
3713 atomic_min, atomic_max,
3714 2,
3715 i16 AtomicI16
3716}
3717#[cfg(target_has_atomic_load_store = "16")]
3718atomic_int! {
3719 cfg(target_has_atomic = "16"),
3720 cfg(target_has_atomic_equal_alignment = "16"),
3721 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3722 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3723 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3724 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3725 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3726 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3727 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3728 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3729 rustc_diagnostic_item = "AtomicU16",
3730 "u16",
3731 "",
3732 atomic_umin, atomic_umax,
3733 2,
3734 u16 AtomicU16
3735}
3736#[cfg(target_has_atomic_load_store = "32")]
3737atomic_int! {
3738 cfg(target_has_atomic = "32"),
3739 cfg(target_has_atomic_equal_alignment = "32"),
3740 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3741 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3742 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3743 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3744 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3745 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3746 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3747 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3748 rustc_diagnostic_item = "AtomicI32",
3749 "i32",
3750 "",
3751 atomic_min, atomic_max,
3752 4,
3753 i32 AtomicI32
3754}
3755#[cfg(target_has_atomic_load_store = "32")]
3756atomic_int! {
3757 cfg(target_has_atomic = "32"),
3758 cfg(target_has_atomic_equal_alignment = "32"),
3759 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3760 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3761 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3762 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3763 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3764 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3765 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3766 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3767 rustc_diagnostic_item = "AtomicU32",
3768 "u32",
3769 "",
3770 atomic_umin, atomic_umax,
3771 4,
3772 u32 AtomicU32
3773}
3774#[cfg(target_has_atomic_load_store = "64")]
3775atomic_int! {
3776 cfg(target_has_atomic = "64"),
3777 cfg(target_has_atomic_equal_alignment = "64"),
3778 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3779 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3780 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3781 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3782 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3783 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3784 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3785 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3786 rustc_diagnostic_item = "AtomicI64",
3787 "i64",
3788 "",
3789 atomic_min, atomic_max,
3790 8,
3791 i64 AtomicI64
3792}
3793#[cfg(target_has_atomic_load_store = "64")]
3794atomic_int! {
3795 cfg(target_has_atomic = "64"),
3796 cfg(target_has_atomic_equal_alignment = "64"),
3797 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3798 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3799 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3800 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3801 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3802 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3803 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3804 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3805 rustc_diagnostic_item = "AtomicU64",
3806 "u64",
3807 "",
3808 atomic_umin, atomic_umax,
3809 8,
3810 u64 AtomicU64
3811}
3812#[cfg(target_has_atomic_load_store = "128")]
3813atomic_int! {
3814 cfg(target_has_atomic = "128"),
3815 cfg(target_has_atomic_equal_alignment = "128"),
3816 unstable(feature = "integer_atomics", issue = "99069"),
3817 unstable(feature = "integer_atomics", issue = "99069"),
3818 unstable(feature = "integer_atomics", issue = "99069"),
3819 unstable(feature = "integer_atomics", issue = "99069"),
3820 unstable(feature = "integer_atomics", issue = "99069"),
3821 unstable(feature = "integer_atomics", issue = "99069"),
3822 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3823 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3824 rustc_diagnostic_item = "AtomicI128",
3825 "i128",
3826 "#![feature(integer_atomics)]\n\n",
3827 atomic_min, atomic_max,
3828 16,
3829 i128 AtomicI128
3830}
3831#[cfg(target_has_atomic_load_store = "128")]
3832atomic_int! {
3833 cfg(target_has_atomic = "128"),
3834 cfg(target_has_atomic_equal_alignment = "128"),
3835 unstable(feature = "integer_atomics", issue = "99069"),
3836 unstable(feature = "integer_atomics", issue = "99069"),
3837 unstable(feature = "integer_atomics", issue = "99069"),
3838 unstable(feature = "integer_atomics", issue = "99069"),
3839 unstable(feature = "integer_atomics", issue = "99069"),
3840 unstable(feature = "integer_atomics", issue = "99069"),
3841 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3842 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3843 rustc_diagnostic_item = "AtomicU128",
3844 "u128",
3845 "#![feature(integer_atomics)]\n\n",
3846 atomic_umin, atomic_umax,
3847 16,
3848 u128 AtomicU128
3849}
3850
3851#[cfg(target_has_atomic_load_store = "ptr")]
3852macro_rules! atomic_int_ptr_sized {
3853 ( $($target_pointer_width:literal $align:literal)* ) => { $(
3854 #[cfg(target_pointer_width = $target_pointer_width)]
3855 atomic_int! {
3856 cfg(target_has_atomic = "ptr"),
3857 cfg(target_has_atomic_equal_alignment = "ptr"),
3858 stable(feature = "rust1", since = "1.0.0"),
3859 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3860 stable(feature = "atomic_debug", since = "1.3.0"),
3861 stable(feature = "atomic_access", since = "1.15.0"),
3862 stable(feature = "atomic_from", since = "1.23.0"),
3863 stable(feature = "atomic_nand", since = "1.27.0"),
3864 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3865 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3866 rustc_diagnostic_item = "AtomicIsize",
3867 "isize",
3868 "",
3869 atomic_min, atomic_max,
3870 $align,
3871 isize AtomicIsize
3872 }
3873 #[cfg(target_pointer_width = $target_pointer_width)]
3874 atomic_int! {
3875 cfg(target_has_atomic = "ptr"),
3876 cfg(target_has_atomic_equal_alignment = "ptr"),
3877 stable(feature = "rust1", since = "1.0.0"),
3878 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3879 stable(feature = "atomic_debug", since = "1.3.0"),
3880 stable(feature = "atomic_access", since = "1.15.0"),
3881 stable(feature = "atomic_from", since = "1.23.0"),
3882 stable(feature = "atomic_nand", since = "1.27.0"),
3883 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3884 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3885 rustc_diagnostic_item = "AtomicUsize",
3886 "usize",
3887 "",
3888 atomic_umin, atomic_umax,
3889 $align,
3890 usize AtomicUsize
3891 }
3892
3893 /// An [`AtomicIsize`] initialized to `0`.
3894 #[cfg(target_pointer_width = $target_pointer_width)]
3895 #[stable(feature = "rust1", since = "1.0.0")]
3896 #[deprecated(
3897 since = "1.34.0",
3898 note = "the `new` function is now preferred",
3899 suggestion = "AtomicIsize::new(0)",
3900 )]
3901 pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0);
3902
3903 /// An [`AtomicUsize`] initialized to `0`.
3904 #[cfg(target_pointer_width = $target_pointer_width)]
3905 #[stable(feature = "rust1", since = "1.0.0")]
3906 #[deprecated(
3907 since = "1.34.0",
3908 note = "the `new` function is now preferred",
3909 suggestion = "AtomicUsize::new(0)",
3910 )]
3911 pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0);
3912 )* };
3913}
3914
3915#[cfg(target_has_atomic_load_store = "ptr")]
3916atomic_int_ptr_sized! {
3917 "16" 2
3918 "32" 4
3919 "64" 8
3920}
3921
3922#[inline]
3923#[cfg(target_has_atomic)]
3924fn strongest_failure_ordering(order: Ordering) -> Ordering {
3925 match order {
3926 Release => Relaxed,
3927 Relaxed => Relaxed,
3928 SeqCst => SeqCst,
3929 Acquire => Acquire,
3930 AcqRel => Acquire,
3931 }
3932}
3933
3934#[inline]
3935#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3936unsafe fn atomic_store<T: Copy>(dst: *mut T, val: T, order: Ordering) {
3937 // SAFETY: the caller must uphold the safety contract for `atomic_store`.
3938 unsafe {
3939 match order {
3940 Relaxed => intrinsics::atomic_store::<T, { AO::Relaxed }>(dst, val),
3941 Release => intrinsics::atomic_store::<T, { AO::Release }>(dst, val),
3942 SeqCst => intrinsics::atomic_store::<T, { AO::SeqCst }>(dst, val),
3943 Acquire => panic!("there is no such thing as an acquire store"),
3944 AcqRel => panic!("there is no such thing as an acquire-release store"),
3945 }
3946 }
3947}
3948
3949#[inline]
3950#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3951unsafe fn atomic_load<T: Copy>(dst: *const T, order: Ordering) -> T {
3952 // SAFETY: the caller must uphold the safety contract for `atomic_load`.
3953 unsafe {
3954 match order {
3955 Relaxed => intrinsics::atomic_load::<T, { AO::Relaxed }>(dst),
3956 Acquire => intrinsics::atomic_load::<T, { AO::Acquire }>(dst),
3957 SeqCst => intrinsics::atomic_load::<T, { AO::SeqCst }>(dst),
3958 Release => panic!("there is no such thing as a release load"),
3959 AcqRel => panic!("there is no such thing as an acquire-release load"),
3960 }
3961 }
3962}
3963
3964#[inline]
3965#[cfg(target_has_atomic)]
3966#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3967unsafe fn atomic_swap<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3968 // SAFETY: the caller must uphold the safety contract for `atomic_swap`.
3969 unsafe {
3970 match order {
3971 Relaxed => intrinsics::atomic_xchg::<T, { AO::Relaxed }>(dst, val),
3972 Acquire => intrinsics::atomic_xchg::<T, { AO::Acquire }>(dst, val),
3973 Release => intrinsics::atomic_xchg::<T, { AO::Release }>(dst, val),
3974 AcqRel => intrinsics::atomic_xchg::<T, { AO::AcqRel }>(dst, val),
3975 SeqCst => intrinsics::atomic_xchg::<T, { AO::SeqCst }>(dst, val),
3976 }
3977 }
3978}
3979
3980/// Returns the previous value (like __sync_fetch_and_add).
3981#[inline]
3982#[cfg(target_has_atomic)]
3983#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3984unsafe fn atomic_add<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3985 // SAFETY: the caller must uphold the safety contract for `atomic_add`.
3986 unsafe {
3987 match order {
3988 Relaxed => intrinsics::atomic_xadd::<T, { AO::Relaxed }>(dst, val),
3989 Acquire => intrinsics::atomic_xadd::<T, { AO::Acquire }>(dst, val),
3990 Release => intrinsics::atomic_xadd::<T, { AO::Release }>(dst, val),
3991 AcqRel => intrinsics::atomic_xadd::<T, { AO::AcqRel }>(dst, val),
3992 SeqCst => intrinsics::atomic_xadd::<T, { AO::SeqCst }>(dst, val),
3993 }
3994 }
3995}
3996
3997/// Returns the previous value (like __sync_fetch_and_sub).
3998#[inline]
3999#[cfg(target_has_atomic)]
4000#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4001unsafe fn atomic_sub<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4002 // SAFETY: the caller must uphold the safety contract for `atomic_sub`.
4003 unsafe {
4004 match order {
4005 Relaxed => intrinsics::atomic_xsub::<T, { AO::Relaxed }>(dst, val),
4006 Acquire => intrinsics::atomic_xsub::<T, { AO::Acquire }>(dst, val),
4007 Release => intrinsics::atomic_xsub::<T, { AO::Release }>(dst, val),
4008 AcqRel => intrinsics::atomic_xsub::<T, { AO::AcqRel }>(dst, val),
4009 SeqCst => intrinsics::atomic_xsub::<T, { AO::SeqCst }>(dst, val),
4010 }
4011 }
4012}
4013
4014/// Publicly exposed for stdarch; nobody else should use this.
4015#[inline]
4016#[cfg(target_has_atomic)]
4017#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4018#[unstable(feature = "core_intrinsics", issue = "none")]
4019#[doc(hidden)]
4020pub unsafe fn atomic_compare_exchange<T: Copy>(
4021 dst: *mut T,
4022 old: T,
4023 new: T,
4024 success: Ordering,
4025 failure: Ordering,
4026) -> Result<T, T> {
4027 // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`.
4028 let (val, ok) = unsafe {
4029 match (success, failure) {
4030 (Relaxed, Relaxed) => {
4031 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4032 }
4033 (Relaxed, Acquire) => {
4034 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4035 }
4036 (Relaxed, SeqCst) => {
4037 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4038 }
4039 (Acquire, Relaxed) => {
4040 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4041 }
4042 (Acquire, Acquire) => {
4043 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4044 }
4045 (Acquire, SeqCst) => {
4046 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4047 }
4048 (Release, Relaxed) => {
4049 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4050 }
4051 (Release, Acquire) => {
4052 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4053 }
4054 (Release, SeqCst) => {
4055 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4056 }
4057 (AcqRel, Relaxed) => {
4058 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4059 }
4060 (AcqRel, Acquire) => {
4061 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4062 }
4063 (AcqRel, SeqCst) => {
4064 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4065 }
4066 (SeqCst, Relaxed) => {
4067 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4068 }
4069 (SeqCst, Acquire) => {
4070 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4071 }
4072 (SeqCst, SeqCst) => {
4073 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4074 }
4075 (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
4076 (_, Release) => panic!("there is no such thing as a release failure ordering"),
4077 }
4078 };
4079 if ok { Ok(val) } else { Err(val) }
4080}
4081
4082#[inline]
4083#[cfg(target_has_atomic)]
4084#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4085unsafe fn atomic_compare_exchange_weak<T: Copy>(
4086 dst: *mut T,
4087 old: T,
4088 new: T,
4089 success: Ordering,
4090 failure: Ordering,
4091) -> Result<T, T> {
4092 // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`.
4093 let (val, ok) = unsafe {
4094 match (success, failure) {
4095 (Relaxed, Relaxed) => {
4096 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4097 }
4098 (Relaxed, Acquire) => {
4099 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4100 }
4101 (Relaxed, SeqCst) => {
4102 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4103 }
4104 (Acquire, Relaxed) => {
4105 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4106 }
4107 (Acquire, Acquire) => {
4108 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4109 }
4110 (Acquire, SeqCst) => {
4111 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4112 }
4113 (Release, Relaxed) => {
4114 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4115 }
4116 (Release, Acquire) => {
4117 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4118 }
4119 (Release, SeqCst) => {
4120 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4121 }
4122 (AcqRel, Relaxed) => {
4123 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4124 }
4125 (AcqRel, Acquire) => {
4126 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4127 }
4128 (AcqRel, SeqCst) => {
4129 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4130 }
4131 (SeqCst, Relaxed) => {
4132 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4133 }
4134 (SeqCst, Acquire) => {
4135 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4136 }
4137 (SeqCst, SeqCst) => {
4138 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4139 }
4140 (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
4141 (_, Release) => panic!("there is no such thing as a release failure ordering"),
4142 }
4143 };
4144 if ok { Ok(val) } else { Err(val) }
4145}
4146
4147#[inline]
4148#[cfg(target_has_atomic)]
4149#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4150unsafe fn atomic_and<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4151 // SAFETY: the caller must uphold the safety contract for `atomic_and`
4152 unsafe {
4153 match order {
4154 Relaxed => intrinsics::atomic_and::<T, { AO::Relaxed }>(dst, val),
4155 Acquire => intrinsics::atomic_and::<T, { AO::Acquire }>(dst, val),
4156 Release => intrinsics::atomic_and::<T, { AO::Release }>(dst, val),
4157 AcqRel => intrinsics::atomic_and::<T, { AO::AcqRel }>(dst, val),
4158 SeqCst => intrinsics::atomic_and::<T, { AO::SeqCst }>(dst, val),
4159 }
4160 }
4161}
4162
4163#[inline]
4164#[cfg(target_has_atomic)]
4165#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4166unsafe fn atomic_nand<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4167 // SAFETY: the caller must uphold the safety contract for `atomic_nand`
4168 unsafe {
4169 match order {
4170 Relaxed => intrinsics::atomic_nand::<T, { AO::Relaxed }>(dst, val),
4171 Acquire => intrinsics::atomic_nand::<T, { AO::Acquire }>(dst, val),
4172 Release => intrinsics::atomic_nand::<T, { AO::Release }>(dst, val),
4173 AcqRel => intrinsics::atomic_nand::<T, { AO::AcqRel }>(dst, val),
4174 SeqCst => intrinsics::atomic_nand::<T, { AO::SeqCst }>(dst, val),
4175 }
4176 }
4177}
4178
4179#[inline]
4180#[cfg(target_has_atomic)]
4181#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4182unsafe fn atomic_or<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4183 // SAFETY: the caller must uphold the safety contract for `atomic_or`
4184 unsafe {
4185 match order {
4186 SeqCst => intrinsics::atomic_or::<T, { AO::SeqCst }>(dst, val),
4187 Acquire => intrinsics::atomic_or::<T, { AO::Acquire }>(dst, val),
4188 Release => intrinsics::atomic_or::<T, { AO::Release }>(dst, val),
4189 AcqRel => intrinsics::atomic_or::<T, { AO::AcqRel }>(dst, val),
4190 Relaxed => intrinsics::atomic_or::<T, { AO::Relaxed }>(dst, val),
4191 }
4192 }
4193}
4194
4195#[inline]
4196#[cfg(target_has_atomic)]
4197#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4198unsafe fn atomic_xor<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4199 // SAFETY: the caller must uphold the safety contract for `atomic_xor`
4200 unsafe {
4201 match order {
4202 SeqCst => intrinsics::atomic_xor::<T, { AO::SeqCst }>(dst, val),
4203 Acquire => intrinsics::atomic_xor::<T, { AO::Acquire }>(dst, val),
4204 Release => intrinsics::atomic_xor::<T, { AO::Release }>(dst, val),
4205 AcqRel => intrinsics::atomic_xor::<T, { AO::AcqRel }>(dst, val),
4206 Relaxed => intrinsics::atomic_xor::<T, { AO::Relaxed }>(dst, val),
4207 }
4208 }
4209}
4210
4211/// Updates `*dst` to the max value of `val` and the old value (signed comparison)
4212#[inline]
4213#[cfg(target_has_atomic)]
4214#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4215unsafe fn atomic_max<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4216 // SAFETY: the caller must uphold the safety contract for `atomic_max`
4217 unsafe {
4218 match order {
4219 Relaxed => intrinsics::atomic_max::<T, { AO::Relaxed }>(dst, val),
4220 Acquire => intrinsics::atomic_max::<T, { AO::Acquire }>(dst, val),
4221 Release => intrinsics::atomic_max::<T, { AO::Release }>(dst, val),
4222 AcqRel => intrinsics::atomic_max::<T, { AO::AcqRel }>(dst, val),
4223 SeqCst => intrinsics::atomic_max::<T, { AO::SeqCst }>(dst, val),
4224 }
4225 }
4226}
4227
4228/// Updates `*dst` to the min value of `val` and the old value (signed comparison)
4229#[inline]
4230#[cfg(target_has_atomic)]
4231#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4232unsafe fn atomic_min<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4233 // SAFETY: the caller must uphold the safety contract for `atomic_min`
4234 unsafe {
4235 match order {
4236 Relaxed => intrinsics::atomic_min::<T, { AO::Relaxed }>(dst, val),
4237 Acquire => intrinsics::atomic_min::<T, { AO::Acquire }>(dst, val),
4238 Release => intrinsics::atomic_min::<T, { AO::Release }>(dst, val),
4239 AcqRel => intrinsics::atomic_min::<T, { AO::AcqRel }>(dst, val),
4240 SeqCst => intrinsics::atomic_min::<T, { AO::SeqCst }>(dst, val),
4241 }
4242 }
4243}
4244
4245/// Updates `*dst` to the max value of `val` and the old value (unsigned comparison)
4246#[inline]
4247#[cfg(target_has_atomic)]
4248#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4249unsafe fn atomic_umax<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4250 // SAFETY: the caller must uphold the safety contract for `atomic_umax`
4251 unsafe {
4252 match order {
4253 Relaxed => intrinsics::atomic_umax::<T, { AO::Relaxed }>(dst, val),
4254 Acquire => intrinsics::atomic_umax::<T, { AO::Acquire }>(dst, val),
4255 Release => intrinsics::atomic_umax::<T, { AO::Release }>(dst, val),
4256 AcqRel => intrinsics::atomic_umax::<T, { AO::AcqRel }>(dst, val),
4257 SeqCst => intrinsics::atomic_umax::<T, { AO::SeqCst }>(dst, val),
4258 }
4259 }
4260}
4261
4262/// Updates `*dst` to the min value of `val` and the old value (unsigned comparison)
4263#[inline]
4264#[cfg(target_has_atomic)]
4265#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4266unsafe fn atomic_umin<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4267 // SAFETY: the caller must uphold the safety contract for `atomic_umin`
4268 unsafe {
4269 match order {
4270 Relaxed => intrinsics::atomic_umin::<T, { AO::Relaxed }>(dst, val),
4271 Acquire => intrinsics::atomic_umin::<T, { AO::Acquire }>(dst, val),
4272 Release => intrinsics::atomic_umin::<T, { AO::Release }>(dst, val),
4273 AcqRel => intrinsics::atomic_umin::<T, { AO::AcqRel }>(dst, val),
4274 SeqCst => intrinsics::atomic_umin::<T, { AO::SeqCst }>(dst, val),
4275 }
4276 }
4277}
4278
4279/// An atomic fence.
4280///
4281/// Fences create synchronization between themselves and atomic operations or fences in other
4282/// threads. To achieve this, a fence prevents the compiler and CPU from reordering certain types of
4283/// memory operations around it.
4284///
4285/// A fence 'A' which has (at least) [`Release`] ordering semantics, synchronizes
4286/// with a fence 'B' with (at least) [`Acquire`] semantics, if and only if there
4287/// exist operations X and Y, both operating on some atomic object 'm' such
4288/// that A is sequenced before X, Y is sequenced before B and Y observes
4289/// the change to m. This provides a happens-before dependence between A and B.
4290///
4291/// ```text
4292/// Thread 1 Thread 2
4293///
4294/// fence(Release); A --------------
4295/// m.store(3, Relaxed); X --------- |
4296/// | |
4297/// | |
4298/// -------------> Y if m.load(Relaxed) == 3 {
4299/// |-------> B fence(Acquire);
4300/// ...
4301/// }
4302/// ```
4303///
4304/// Note that in the example above, it is crucial that the accesses to `m` are atomic. Fences cannot
4305/// be used to establish synchronization among non-atomic accesses in different threads. However,
4306/// thanks to the happens-before relationship between A and B, any non-atomic accesses that
4307/// happen-before A are now also properly synchronized with any non-atomic accesses that
4308/// happen-after B.
4309///
4310/// Atomic operations with [`Release`] or [`Acquire`] semantics can also synchronize
4311/// with a fence.
4312///
4313/// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`]
4314/// and [`Release`] semantics, participates in the global program order of the
4315/// other [`SeqCst`] operations and/or fences.
4316///
4317/// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings.
4318///
4319/// # Panics
4320///
4321/// Panics if `order` is [`Relaxed`].
4322///
4323/// # Examples
4324///
4325/// ```
4326/// use std::sync::atomic::AtomicBool;
4327/// use std::sync::atomic::fence;
4328/// use std::sync::atomic::Ordering;
4329///
4330/// // A mutual exclusion primitive based on spinlock.
4331/// pub struct Mutex {
4332/// flag: AtomicBool,
4333/// }
4334///
4335/// impl Mutex {
4336/// pub fn new() -> Mutex {
4337/// Mutex {
4338/// flag: AtomicBool::new(false),
4339/// }
4340/// }
4341///
4342/// pub fn lock(&self) {
4343/// // Wait until the old value is `false`.
4344/// while self
4345/// .flag
4346/// .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
4347/// .is_err()
4348/// {}
4349/// // This fence synchronizes-with store in `unlock`.
4350/// fence(Ordering::Acquire);
4351/// }
4352///
4353/// pub fn unlock(&self) {
4354/// self.flag.store(false, Ordering::Release);
4355/// }
4356/// }
4357/// ```
4358#[inline]
4359#[stable(feature = "rust1", since = "1.0.0")]
4360#[rustc_diagnostic_item = "fence"]
4361#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4362pub fn fence(order: Ordering) {
4363 // SAFETY: using an atomic fence is safe.
4364 unsafe {
4365 match order {
4366 Acquire => intrinsics::atomic_fence::<{ AO::Acquire }>(),
4367 Release => intrinsics::atomic_fence::<{ AO::Release }>(),
4368 AcqRel => intrinsics::atomic_fence::<{ AO::AcqRel }>(),
4369 SeqCst => intrinsics::atomic_fence::<{ AO::SeqCst }>(),
4370 Relaxed => panic!("there is no such thing as a relaxed fence"),
4371 }
4372 }
4373}
4374
4375/// A "compiler-only" atomic fence.
4376///
4377/// Like [`fence`], this function establishes synchronization with other atomic operations and
4378/// fences. However, unlike [`fence`], `compiler_fence` only establishes synchronization with
4379/// operations *in the same thread*. This may at first sound rather useless, since code within a
4380/// thread is typically already totally ordered and does not need any further synchronization.
4381/// However, there are cases where code can run on the same thread without being ordered:
4382/// - The most common case is that of a *signal handler*: a signal handler runs in the same thread
4383/// as the code it interrupted, but it is not ordered with respect to that code. `compiler_fence`
4384/// can be used to establish synchronization between a thread and its signal handler, the same way
4385/// that `fence` can be used to establish synchronization across threads.
4386/// - Similar situations can arise in embedded programming with interrupt handlers, or in custom
4387/// implementations of preemptive green threads. In general, `compiler_fence` can establish
4388/// synchronization with code that is guaranteed to run on the same hardware CPU.
4389///
4390/// See [`fence`] for how a fence can be used to achieve synchronization. Note that just like
4391/// [`fence`], synchronization still requires atomic operations to be used in both threads -- it is
4392/// not possible to perform synchronization entirely with fences and non-atomic operations.
4393///
4394/// `compiler_fence` does not emit any machine code, but restricts the kinds of memory re-ordering
4395/// the compiler is allowed to do. `compiler_fence` corresponds to [`atomic_signal_fence`] in C and
4396/// C++.
4397///
4398/// [`atomic_signal_fence`]: https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence
4399///
4400/// # Panics
4401///
4402/// Panics if `order` is [`Relaxed`].
4403///
4404/// # Examples
4405///
4406/// Without the two `compiler_fence` calls, the read of `IMPORTANT_VARIABLE` in `signal_handler`
4407/// is *undefined behavior* due to a data race, despite everything happening in a single thread.
4408/// This is because the signal handler is considered to run concurrently with its associated
4409/// thread, and explicit synchronization is required to pass data between a thread and its
4410/// signal handler. The code below uses two `compiler_fence` calls to establish the usual
4411/// release-acquire synchronization pattern (see [`fence`] for an image).
4412///
4413/// ```
4414/// use std::sync::atomic::AtomicBool;
4415/// use std::sync::atomic::Ordering;
4416/// use std::sync::atomic::compiler_fence;
4417///
4418/// static mut IMPORTANT_VARIABLE: usize = 0;
4419/// static IS_READY: AtomicBool = AtomicBool::new(false);
4420///
4421/// fn main() {
4422/// unsafe { IMPORTANT_VARIABLE = 42 };
4423/// // Marks earlier writes as being released with future relaxed stores.
4424/// compiler_fence(Ordering::Release);
4425/// IS_READY.store(true, Ordering::Relaxed);
4426/// }
4427///
4428/// fn signal_handler() {
4429/// if IS_READY.load(Ordering::Relaxed) {
4430/// // Acquires writes that were released with relaxed stores that we read from.
4431/// compiler_fence(Ordering::Acquire);
4432/// assert_eq!(unsafe { IMPORTANT_VARIABLE }, 42);
4433/// }
4434/// }
4435/// ```
4436#[inline]
4437#[stable(feature = "compiler_fences", since = "1.21.0")]
4438#[rustc_diagnostic_item = "compiler_fence"]
4439#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4440pub fn compiler_fence(order: Ordering) {
4441 // SAFETY: using an atomic fence is safe.
4442 unsafe {
4443 match order {
4444 Acquire => intrinsics::atomic_singlethreadfence::<{ AO::Acquire }>(),
4445 Release => intrinsics::atomic_singlethreadfence::<{ AO::Release }>(),
4446 AcqRel => intrinsics::atomic_singlethreadfence::<{ AO::AcqRel }>(),
4447 SeqCst => intrinsics::atomic_singlethreadfence::<{ AO::SeqCst }>(),
4448 Relaxed => panic!("there is no such thing as a relaxed fence"),
4449 }
4450 }
4451}
4452
4453#[cfg(target_has_atomic_load_store = "8")]
4454#[stable(feature = "atomic_debug", since = "1.3.0")]
4455impl fmt::Debug for AtomicBool {
4456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4457 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4458 }
4459}
4460
4461#[cfg(target_has_atomic_load_store = "ptr")]
4462#[stable(feature = "atomic_debug", since = "1.3.0")]
4463impl<T> fmt::Debug for AtomicPtr<T> {
4464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4465 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4466 }
4467}
4468
4469#[cfg(target_has_atomic_load_store = "ptr")]
4470#[stable(feature = "atomic_pointer", since = "1.24.0")]
4471impl<T> fmt::Pointer for AtomicPtr<T> {
4472 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4473 fmt::Pointer::fmt(&self.load(Ordering::Relaxed), f)
4474 }
4475}
4476
4477/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock").
4478///
4479/// This function is deprecated in favor of [`hint::spin_loop`].
4480///
4481/// [`hint::spin_loop`]: crate::hint::spin_loop
4482#[inline]
4483#[stable(feature = "spin_loop_hint", since = "1.24.0")]
4484#[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")]
4485pub fn spin_loop_hint() {
4486 spin_loop()
4487}