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