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