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