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