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
1284 /// requirements of the [memory model].
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]: 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 /// use core::sync::atomic::{AtomicPtr, Ordering};
2239 ///
2240 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2241 /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0);
2242 /// // Note: units of `size_of::<i64>()`.
2243 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8);
2244 /// ```
2245 #[inline]
2246 #[cfg(target_has_atomic = "ptr")]
2247 #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
2248 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2249 pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T {
2250 self.fetch_byte_add(val.wrapping_mul(size_of::<T>()), order)
2251 }
2252
2253 /// Offsets the pointer's address by subtracting `val` (in units of `T`),
2254 /// returning the previous pointer.
2255 ///
2256 /// This is equivalent to using [`wrapping_sub`] to atomically perform the
2257 /// equivalent of `ptr = ptr.wrapping_sub(val);`.
2258 ///
2259 /// This method operates in units of `T`, which means that it cannot be used
2260 /// to offset the pointer by an amount which is not a multiple of
2261 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
2262 /// work with a deliberately misaligned pointer. In such cases, you may use
2263 /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead.
2264 ///
2265 /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory
2266 /// ordering of this operation. All ordering modes are possible. Note that
2267 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2268 /// and using [`Release`] makes the load part [`Relaxed`].
2269 ///
2270 /// **Note**: This method is only available on platforms that support atomic
2271 /// operations on [`AtomicPtr`].
2272 ///
2273 /// [`wrapping_sub`]: pointer::wrapping_sub
2274 ///
2275 /// # Examples
2276 ///
2277 /// ```
2278 /// use core::sync::atomic::{AtomicPtr, Ordering};
2279 ///
2280 /// let array = [1i32, 2i32];
2281 /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _);
2282 ///
2283 /// assert!(core::ptr::eq(
2284 /// atom.fetch_ptr_sub(1, Ordering::Relaxed),
2285 /// &array[1],
2286 /// ));
2287 /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0]));
2288 /// ```
2289 #[inline]
2290 #[cfg(target_has_atomic = "ptr")]
2291 #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
2292 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2293 pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T {
2294 self.fetch_byte_sub(val.wrapping_mul(size_of::<T>()), order)
2295 }
2296
2297 /// Offsets the pointer's address by adding `val` *bytes*, returning the
2298 /// previous pointer.
2299 ///
2300 /// This is equivalent to using [`wrapping_byte_add`] to atomically
2301 /// perform `ptr = ptr.wrapping_byte_add(val)`.
2302 ///
2303 /// `fetch_byte_add` takes an [`Ordering`] argument which describes the
2304 /// memory ordering of this operation. All ordering modes are possible. Note
2305 /// that using [`Acquire`] makes the store part of this operation
2306 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2307 ///
2308 /// **Note**: This method is only available on platforms that support atomic
2309 /// operations on [`AtomicPtr`].
2310 ///
2311 /// [`wrapping_byte_add`]: pointer::wrapping_byte_add
2312 ///
2313 /// # Examples
2314 ///
2315 /// ```
2316 /// use core::sync::atomic::{AtomicPtr, Ordering};
2317 ///
2318 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
2319 /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0);
2320 /// // Note: in units of bytes, not `size_of::<i64>()`.
2321 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1);
2322 /// ```
2323 #[inline]
2324 #[cfg(target_has_atomic = "ptr")]
2325 #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
2326 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2327 pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T {
2328 // SAFETY: data races are prevented by atomic intrinsics.
2329 unsafe { atomic_add(self.p.get(), val, order).cast() }
2330 }
2331
2332 /// Offsets the pointer's address by subtracting `val` *bytes*, returning the
2333 /// previous pointer.
2334 ///
2335 /// This is equivalent to using [`wrapping_byte_sub`] to atomically
2336 /// perform `ptr = ptr.wrapping_byte_sub(val)`.
2337 ///
2338 /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the
2339 /// memory ordering of this operation. All ordering modes are possible. Note
2340 /// that using [`Acquire`] makes the store part of this operation
2341 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
2342 ///
2343 /// **Note**: This method is only available on platforms that support atomic
2344 /// operations on [`AtomicPtr`].
2345 ///
2346 /// [`wrapping_byte_sub`]: pointer::wrapping_byte_sub
2347 ///
2348 /// # Examples
2349 ///
2350 /// ```
2351 /// use core::sync::atomic::{AtomicPtr, Ordering};
2352 ///
2353 /// let mut arr = [0i64, 1];
2354 /// let atom = AtomicPtr::<i64>::new(&raw mut arr[1]);
2355 /// assert_eq!(atom.fetch_byte_sub(8, Ordering::Relaxed).addr(), (&raw const arr[1]).addr());
2356 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), (&raw const arr[0]).addr());
2357 /// ```
2358 #[inline]
2359 #[cfg(target_has_atomic = "ptr")]
2360 #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
2361 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2362 pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T {
2363 // SAFETY: data races are prevented by atomic intrinsics.
2364 unsafe { atomic_sub(self.p.get(), val, order).cast() }
2365 }
2366
2367 /// Performs a bitwise "or" operation on the address of the current pointer,
2368 /// and the argument `val`, and stores a pointer with provenance of the
2369 /// current pointer and the resulting address.
2370 ///
2371 /// This is equivalent to using [`map_addr`] to atomically perform
2372 /// `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged
2373 /// pointer schemes to atomically set tag bits.
2374 ///
2375 /// **Caveat**: This operation returns the previous value. To compute the
2376 /// stored value without losing provenance, you may use [`map_addr`]. For
2377 /// example: `a.fetch_or(val).map_addr(|a| a | val)`.
2378 ///
2379 /// `fetch_or` takes an [`Ordering`] argument which describes the memory
2380 /// ordering of this operation. All ordering modes are possible. Note that
2381 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2382 /// and using [`Release`] makes the load part [`Relaxed`].
2383 ///
2384 /// **Note**: This method is only available on platforms that support atomic
2385 /// operations on [`AtomicPtr`].
2386 ///
2387 /// This API and its claimed semantics are part of the Strict Provenance
2388 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2389 /// details.
2390 ///
2391 /// [`map_addr`]: pointer::map_addr
2392 ///
2393 /// # Examples
2394 ///
2395 /// ```
2396 /// use core::sync::atomic::{AtomicPtr, Ordering};
2397 ///
2398 /// let pointer = &mut 3i64 as *mut i64;
2399 ///
2400 /// let atom = AtomicPtr::<i64>::new(pointer);
2401 /// // Tag the bottom bit of the pointer.
2402 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0);
2403 /// // Extract and untag.
2404 /// let tagged = atom.load(Ordering::Relaxed);
2405 /// assert_eq!(tagged.addr() & 1, 1);
2406 /// assert_eq!(tagged.map_addr(|p| p & !1), pointer);
2407 /// ```
2408 #[inline]
2409 #[cfg(target_has_atomic = "ptr")]
2410 #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
2411 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2412 pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T {
2413 // SAFETY: data races are prevented by atomic intrinsics.
2414 unsafe { atomic_or(self.p.get(), val, order).cast() }
2415 }
2416
2417 /// Performs a bitwise "and" operation on the address of the current
2418 /// pointer, and the argument `val`, and stores a pointer with provenance of
2419 /// the current pointer and the resulting address.
2420 ///
2421 /// This is equivalent to using [`map_addr`] to atomically perform
2422 /// `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged
2423 /// pointer schemes to atomically unset tag bits.
2424 ///
2425 /// **Caveat**: This operation returns the previous value. To compute the
2426 /// stored value without losing provenance, you may use [`map_addr`]. For
2427 /// example: `a.fetch_and(val).map_addr(|a| a & val)`.
2428 ///
2429 /// `fetch_and` takes an [`Ordering`] argument which describes the memory
2430 /// ordering of this operation. All ordering modes are possible. Note that
2431 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2432 /// and using [`Release`] makes the load part [`Relaxed`].
2433 ///
2434 /// **Note**: This method is only available on platforms that support atomic
2435 /// operations on [`AtomicPtr`].
2436 ///
2437 /// This API and its claimed semantics are part of the Strict Provenance
2438 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2439 /// details.
2440 ///
2441 /// [`map_addr`]: pointer::map_addr
2442 ///
2443 /// # Examples
2444 ///
2445 /// ```
2446 /// use core::sync::atomic::{AtomicPtr, Ordering};
2447 ///
2448 /// let pointer = &mut 3i64 as *mut i64;
2449 /// // A tagged pointer
2450 /// let atom = AtomicPtr::<i64>::new(pointer.map_addr(|a| a | 1));
2451 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1);
2452 /// // Untag, and extract the previously tagged pointer.
2453 /// let untagged = atom.fetch_and(!1, Ordering::Relaxed)
2454 /// .map_addr(|a| a & !1);
2455 /// assert_eq!(untagged, pointer);
2456 /// ```
2457 #[inline]
2458 #[cfg(target_has_atomic = "ptr")]
2459 #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
2460 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2461 pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T {
2462 // SAFETY: data races are prevented by atomic intrinsics.
2463 unsafe { atomic_and(self.p.get(), val, order).cast() }
2464 }
2465
2466 /// Performs a bitwise "xor" operation on the address of the current
2467 /// pointer, and the argument `val`, and stores a pointer with provenance of
2468 /// the current pointer and the resulting address.
2469 ///
2470 /// This is equivalent to using [`map_addr`] to atomically perform
2471 /// `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged
2472 /// pointer schemes to atomically toggle tag bits.
2473 ///
2474 /// **Caveat**: This operation returns the previous value. To compute the
2475 /// stored value without losing provenance, you may use [`map_addr`]. For
2476 /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`.
2477 ///
2478 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory
2479 /// ordering of this operation. All ordering modes are possible. Note that
2480 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
2481 /// and using [`Release`] makes the load part [`Relaxed`].
2482 ///
2483 /// **Note**: This method is only available on platforms that support atomic
2484 /// operations on [`AtomicPtr`].
2485 ///
2486 /// This API and its claimed semantics are part of the Strict Provenance
2487 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
2488 /// details.
2489 ///
2490 /// [`map_addr`]: pointer::map_addr
2491 ///
2492 /// # Examples
2493 ///
2494 /// ```
2495 /// use core::sync::atomic::{AtomicPtr, Ordering};
2496 ///
2497 /// let pointer = &mut 3i64 as *mut i64;
2498 /// let atom = AtomicPtr::<i64>::new(pointer);
2499 ///
2500 /// // Toggle a tag bit on the pointer.
2501 /// atom.fetch_xor(1, Ordering::Relaxed);
2502 /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1);
2503 /// ```
2504 #[inline]
2505 #[cfg(target_has_atomic = "ptr")]
2506 #[stable(feature = "strict_provenance_atomic_ptr", since = "CURRENT_RUSTC_VERSION")]
2507 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2508 pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T {
2509 // SAFETY: data races are prevented by atomic intrinsics.
2510 unsafe { atomic_xor(self.p.get(), val, order).cast() }
2511 }
2512
2513 /// Returns a mutable pointer to the underlying pointer.
2514 ///
2515 /// Doing non-atomic reads and writes on the resulting pointer can be a data race.
2516 /// This method is mostly useful for FFI, where the function signature may use
2517 /// `*mut *mut T` instead of `&AtomicPtr<T>`.
2518 ///
2519 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
2520 /// atomic types work with interior mutability. All modifications of an atomic change the value
2521 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
2522 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
2523 /// requirements of the [memory model].
2524 ///
2525 /// # Examples
2526 ///
2527 /// ```ignore (extern-declaration)
2528 /// use std::sync::atomic::AtomicPtr;
2529 ///
2530 /// extern "C" {
2531 /// fn my_atomic_op(arg: *mut *mut u32);
2532 /// }
2533 ///
2534 /// let mut value = 17;
2535 /// let atomic = AtomicPtr::new(&mut value);
2536 ///
2537 /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
2538 /// unsafe {
2539 /// my_atomic_op(atomic.as_ptr());
2540 /// }
2541 /// ```
2542 ///
2543 /// [memory model]: self#memory-model-for-atomic-accesses
2544 #[inline]
2545 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
2546 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
2547 #[rustc_never_returns_null_ptr]
2548 pub const fn as_ptr(&self) -> *mut *mut T {
2549 self.p.get()
2550 }
2551}
2552
2553#[cfg(target_has_atomic_load_store = "8")]
2554#[stable(feature = "atomic_bool_from", since = "1.24.0")]
2555#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2556#[cfg(not(feature = "ferrocene_certified"))]
2557impl const From<bool> for AtomicBool {
2558 /// Converts a `bool` into an `AtomicBool`.
2559 ///
2560 /// # Examples
2561 ///
2562 /// ```
2563 /// use std::sync::atomic::AtomicBool;
2564 /// let atomic_bool = AtomicBool::from(true);
2565 /// assert_eq!(format!("{atomic_bool:?}"), "true")
2566 /// ```
2567 #[inline]
2568 fn from(b: bool) -> Self {
2569 Self::new(b)
2570 }
2571}
2572
2573#[cfg(target_has_atomic_load_store = "ptr")]
2574#[stable(feature = "atomic_from", since = "1.23.0")]
2575#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2576#[cfg(not(feature = "ferrocene_certified"))]
2577impl<T> const From<*mut T> for AtomicPtr<T> {
2578 /// Converts a `*mut T` into an `AtomicPtr<T>`.
2579 #[inline]
2580 fn from(p: *mut T) -> Self {
2581 Self::new(p)
2582 }
2583}
2584
2585#[allow(unused_macros)] // This macro ends up being unused on some architectures.
2586macro_rules! if_8_bit {
2587 (u8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2588 (i8, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($yes)*)?) };
2589 ($_:ident, $( yes = [$($yes:tt)*], )? $( no = [$($no:tt)*], )? ) => { concat!("", $($($no)*)?) };
2590}
2591
2592#[cfg(target_has_atomic_load_store)]
2593macro_rules! atomic_int {
2594 ($cfg_cas:meta,
2595 $cfg_align:meta,
2596 $stable:meta,
2597 $stable_cxchg:meta,
2598 $stable_debug:meta,
2599 $stable_access:meta,
2600 $stable_from:meta,
2601 $stable_nand:meta,
2602 $const_stable_new:meta,
2603 $const_stable_into_inner:meta,
2604 $diagnostic_item:meta,
2605 $s_int_type:literal,
2606 $extra_feature:expr,
2607 $min_fn:ident, $max_fn:ident,
2608 $align:expr,
2609 $int_type:ident $atomic_type:ident) => {
2610 /// An integer type which can be safely shared between threads.
2611 ///
2612 /// This type has the same
2613 #[doc = if_8_bit!(
2614 $int_type,
2615 yes = ["size, alignment, and bit validity"],
2616 no = ["size and bit validity"],
2617 )]
2618 /// as the underlying integer type, [`
2619 #[doc = $s_int_type]
2620 /// `].
2621 #[doc = if_8_bit! {
2622 $int_type,
2623 no = [
2624 "However, the alignment of this type is always equal to its ",
2625 "size, even on targets where [`", $s_int_type, "`] has a ",
2626 "lesser alignment."
2627 ],
2628 }]
2629 ///
2630 /// For more about the differences between atomic types and
2631 /// non-atomic types as well as information about the portability of
2632 /// this type, please see the [module-level documentation].
2633 ///
2634 /// **Note:** This type is only available on platforms that support
2635 /// atomic loads and stores of [`
2636 #[doc = $s_int_type]
2637 /// `].
2638 ///
2639 /// [module-level documentation]: crate::sync::atomic
2640 #[$stable]
2641 #[$diagnostic_item]
2642 #[repr(C, align($align))]
2643 pub struct $atomic_type {
2644 v: UnsafeCell<$int_type>,
2645 }
2646
2647 #[$stable]
2648 impl Default for $atomic_type {
2649 #[inline]
2650 fn default() -> Self {
2651 Self::new(Default::default())
2652 }
2653 }
2654
2655 #[$stable_from]
2656 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
2657 impl const From<$int_type> for $atomic_type {
2658 #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")]
2659 #[inline]
2660 fn from(v: $int_type) -> Self { Self::new(v) }
2661 }
2662
2663 #[$stable_debug]
2664 #[cfg(not(feature = "ferrocene_certified"))]
2665 impl fmt::Debug for $atomic_type {
2666 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2667 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
2668 }
2669 }
2670
2671 // Send is implicitly implemented.
2672 #[$stable]
2673 unsafe impl Sync for $atomic_type {}
2674
2675 impl $atomic_type {
2676 /// Creates a new atomic integer.
2677 ///
2678 /// # Examples
2679 ///
2680 /// ```
2681 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2682 ///
2683 #[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")]
2684 /// ```
2685 #[inline]
2686 #[$stable]
2687 #[$const_stable_new]
2688 #[must_use]
2689 pub const fn new(v: $int_type) -> Self {
2690 Self {v: UnsafeCell::new(v)}
2691 }
2692
2693 /// Creates a new reference to an atomic integer from a pointer.
2694 ///
2695 /// # Examples
2696 ///
2697 /// ```
2698 #[doc = concat!($extra_feature, "use std::sync::atomic::{self, ", stringify!($atomic_type), "};")]
2699 ///
2700 /// // Get a pointer to an allocated value
2701 #[doc = concat!("let ptr: *mut ", stringify!($int_type), " = Box::into_raw(Box::new(0));")]
2702 ///
2703 #[doc = concat!("assert!(ptr.cast::<", stringify!($atomic_type), ">().is_aligned());")]
2704 ///
2705 /// {
2706 /// // Create an atomic view of the allocated value
2707 // SAFETY: this is a doc comment, tidy, it can't hurt you (also guaranteed by the construction of `ptr` and the assert above)
2708 #[doc = concat!(" let atomic = unsafe {", stringify!($atomic_type), "::from_ptr(ptr) };")]
2709 ///
2710 /// // Use `atomic` for atomic operations, possibly share it with other threads
2711 /// atomic.store(1, atomic::Ordering::Relaxed);
2712 /// }
2713 ///
2714 /// // It's ok to non-atomically access the value behind `ptr`,
2715 /// // since the reference to the atomic ended its lifetime in the block above
2716 /// assert_eq!(unsafe { *ptr }, 1);
2717 ///
2718 /// // Deallocate the value
2719 /// unsafe { drop(Box::from_raw(ptr)) }
2720 /// ```
2721 ///
2722 /// # Safety
2723 ///
2724 /// * `ptr` must be aligned to
2725 #[doc = concat!(" `align_of::<", stringify!($atomic_type), ">()`")]
2726 #[doc = if_8_bit!{
2727 $int_type,
2728 yes = [
2729 " (note that this is always true, since `align_of::<",
2730 stringify!($atomic_type), ">() == 1`)."
2731 ],
2732 no = [
2733 " (note that on some platforms this can be bigger than `align_of::<",
2734 stringify!($int_type), ">()`)."
2735 ],
2736 }]
2737 /// * `ptr` must be [valid] for both reads and writes for the whole lifetime `'a`.
2738 /// * You must adhere to the [Memory model for atomic accesses]. In particular, it is not
2739 /// allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different
2740 /// sizes, without synchronization.
2741 ///
2742 /// [valid]: crate::ptr#safety
2743 /// [Memory model for atomic accesses]: self#memory-model-for-atomic-accesses
2744 #[inline]
2745 #[stable(feature = "atomic_from_ptr", since = "1.75.0")]
2746 #[rustc_const_stable(feature = "const_atomic_from_ptr", since = "1.84.0")]
2747 pub const unsafe fn from_ptr<'a>(ptr: *mut $int_type) -> &'a $atomic_type {
2748 // SAFETY: guaranteed by the caller
2749 unsafe { &*ptr.cast() }
2750 }
2751
2752
2753 /// Returns a mutable reference to the underlying integer.
2754 ///
2755 /// This is safe because the mutable reference guarantees that no other threads are
2756 /// concurrently accessing the atomic data.
2757 ///
2758 /// # Examples
2759 ///
2760 /// ```
2761 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2762 ///
2763 #[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")]
2764 /// assert_eq!(*some_var.get_mut(), 10);
2765 /// *some_var.get_mut() = 5;
2766 /// assert_eq!(some_var.load(Ordering::SeqCst), 5);
2767 /// ```
2768 #[inline]
2769 #[$stable_access]
2770 pub fn get_mut(&mut self) -> &mut $int_type {
2771 self.v.get_mut()
2772 }
2773
2774 #[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")]
2775 ///
2776 #[doc = if_8_bit! {
2777 $int_type,
2778 no = [
2779 "**Note:** This function is only available on targets where `",
2780 stringify!($atomic_type), "` has the same alignment as `", stringify!($int_type), "`."
2781 ],
2782 }]
2783 ///
2784 /// # Examples
2785 ///
2786 /// ```
2787 /// #![feature(atomic_from_mut)]
2788 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2789 ///
2790 /// let mut some_int = 123;
2791 #[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")]
2792 /// a.store(100, Ordering::Relaxed);
2793 /// assert_eq!(some_int, 100);
2794 /// ```
2795 ///
2796 #[inline]
2797 #[$cfg_align]
2798 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2799 pub fn from_mut(v: &mut $int_type) -> &mut Self {
2800 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2801 // SAFETY:
2802 // - the mutable reference guarantees unique ownership.
2803 // - the alignment of `$int_type` and `Self` is the
2804 // same, as promised by $cfg_align and verified above.
2805 unsafe { &mut *(v as *mut $int_type as *mut Self) }
2806 }
2807
2808 #[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")]
2809 ///
2810 /// This is safe because the mutable reference guarantees that no other threads are
2811 /// concurrently accessing the atomic data.
2812 ///
2813 /// # Examples
2814 ///
2815 /// ```ignore-wasm
2816 /// #![feature(atomic_from_mut)]
2817 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2818 ///
2819 #[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")]
2820 ///
2821 #[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")]
2822 /// assert_eq!(view, [0; 10]);
2823 /// view
2824 /// .iter_mut()
2825 /// .enumerate()
2826 /// .for_each(|(idx, int)| *int = idx as _);
2827 ///
2828 /// std::thread::scope(|s| {
2829 /// some_ints
2830 /// .iter()
2831 /// .enumerate()
2832 /// .for_each(|(idx, int)| {
2833 /// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
2834 /// })
2835 /// });
2836 /// ```
2837 #[inline]
2838 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2839 pub fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] {
2840 // SAFETY: the mutable reference guarantees unique ownership.
2841 unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) }
2842 }
2843
2844 #[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")]
2845 ///
2846 /// # Examples
2847 ///
2848 /// ```ignore-wasm
2849 /// #![feature(atomic_from_mut)]
2850 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2851 ///
2852 /// let mut some_ints = [0; 10];
2853 #[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")]
2854 /// std::thread::scope(|s| {
2855 /// for i in 0..a.len() {
2856 /// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
2857 /// }
2858 /// });
2859 /// for (i, n) in some_ints.into_iter().enumerate() {
2860 /// assert_eq!(i, n as usize);
2861 /// }
2862 /// ```
2863 #[inline]
2864 #[$cfg_align]
2865 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2866 pub fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] {
2867 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2868 // SAFETY:
2869 // - the mutable reference guarantees unique ownership.
2870 // - the alignment of `$int_type` and `Self` is the
2871 // same, as promised by $cfg_align and verified above.
2872 unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) }
2873 }
2874
2875 /// Consumes the atomic and returns the contained value.
2876 ///
2877 /// This is safe because passing `self` by value guarantees that no other threads are
2878 /// concurrently accessing the atomic data.
2879 ///
2880 /// # Examples
2881 ///
2882 /// ```
2883 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2884 ///
2885 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2886 /// assert_eq!(some_var.into_inner(), 5);
2887 /// ```
2888 #[inline]
2889 #[$stable_access]
2890 #[$const_stable_into_inner]
2891 pub const fn into_inner(self) -> $int_type {
2892 self.v.into_inner()
2893 }
2894
2895 /// Loads a value from the atomic integer.
2896 ///
2897 /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2898 /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
2899 ///
2900 /// # Panics
2901 ///
2902 /// Panics if `order` is [`Release`] or [`AcqRel`].
2903 ///
2904 /// # Examples
2905 ///
2906 /// ```
2907 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2908 ///
2909 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2910 ///
2911 /// assert_eq!(some_var.load(Ordering::Relaxed), 5);
2912 /// ```
2913 #[inline]
2914 #[$stable]
2915 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2916 pub fn load(&self, order: Ordering) -> $int_type {
2917 // SAFETY: data races are prevented by atomic intrinsics.
2918 unsafe { atomic_load(self.v.get(), order) }
2919 }
2920
2921 /// Stores a value into the atomic integer.
2922 ///
2923 /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2924 /// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
2925 ///
2926 /// # Panics
2927 ///
2928 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
2929 ///
2930 /// # Examples
2931 ///
2932 /// ```
2933 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2934 ///
2935 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2936 ///
2937 /// some_var.store(10, Ordering::Relaxed);
2938 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2939 /// ```
2940 #[inline]
2941 #[$stable]
2942 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2943 pub fn store(&self, val: $int_type, order: Ordering) {
2944 // SAFETY: data races are prevented by atomic intrinsics.
2945 unsafe { atomic_store(self.v.get(), val, order); }
2946 }
2947
2948 /// Stores a value into the atomic integer, returning the previous value.
2949 ///
2950 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
2951 /// of this operation. All ordering modes are possible. Note that using
2952 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2953 /// using [`Release`] makes the load part [`Relaxed`].
2954 ///
2955 /// **Note**: This method is only available on platforms that support atomic operations on
2956 #[doc = concat!("[`", $s_int_type, "`].")]
2957 ///
2958 /// # Examples
2959 ///
2960 /// ```
2961 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2962 ///
2963 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2964 ///
2965 /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
2966 /// ```
2967 #[inline]
2968 #[$stable]
2969 #[$cfg_cas]
2970 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
2971 pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
2972 // SAFETY: data races are prevented by atomic intrinsics.
2973 unsafe { atomic_swap(self.v.get(), val, order) }
2974 }
2975
2976 /// Stores a value into the atomic integer if the current value is the same as
2977 /// the `current` value.
2978 ///
2979 /// The return value is always the previous value. If it is equal to `current`, then the
2980 /// value was updated.
2981 ///
2982 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
2983 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
2984 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
2985 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
2986 /// happens, and using [`Release`] makes the load part [`Relaxed`].
2987 ///
2988 /// **Note**: This method is only available on platforms that support atomic operations on
2989 #[doc = concat!("[`", $s_int_type, "`].")]
2990 ///
2991 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
2992 ///
2993 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
2994 /// memory orderings:
2995 ///
2996 /// Original | Success | Failure
2997 /// -------- | ------- | -------
2998 /// Relaxed | Relaxed | Relaxed
2999 /// Acquire | Acquire | Acquire
3000 /// Release | Release | Relaxed
3001 /// AcqRel | AcqRel | Acquire
3002 /// SeqCst | SeqCst | SeqCst
3003 ///
3004 /// `compare_and_swap` and `compare_exchange` also differ in their return type. You can use
3005 /// `compare_exchange(...).unwrap_or_else(|x| x)` to recover the behavior of `compare_and_swap`,
3006 /// but in most cases it is more idiomatic to check whether the return value is `Ok` or `Err`
3007 /// rather than to infer success vs failure based on the value that was read.
3008 ///
3009 /// During migration, consider whether it makes sense to use `compare_exchange_weak` instead.
3010 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
3011 /// which allows the compiler to generate better assembly code when the compare and swap
3012 /// is used in a loop.
3013 ///
3014 /// # Examples
3015 ///
3016 /// ```
3017 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3018 ///
3019 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
3020 ///
3021 /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
3022 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3023 ///
3024 /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
3025 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3026 /// ```
3027 #[inline]
3028 #[$stable]
3029 #[deprecated(
3030 since = "1.50.0",
3031 note = "Use `compare_exchange` or `compare_exchange_weak` instead")
3032 ]
3033 #[$cfg_cas]
3034 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3035 pub fn compare_and_swap(&self,
3036 current: $int_type,
3037 new: $int_type,
3038 order: Ordering) -> $int_type {
3039 match self.compare_exchange(current,
3040 new,
3041 order,
3042 strongest_failure_ordering(order)) {
3043 Ok(x) => x,
3044 Err(x) => x,
3045 }
3046 }
3047
3048 /// Stores a value into the atomic integer if the current value is the same as
3049 /// the `current` value.
3050 ///
3051 /// The return value is a result indicating whether the new value was written and
3052 /// containing the previous value. On success this value is guaranteed to be equal to
3053 /// `current`.
3054 ///
3055 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
3056 /// ordering of this operation. `success` describes the required ordering for the
3057 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3058 /// `failure` describes the required ordering for the load operation that takes place when
3059 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3060 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3061 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3062 ///
3063 /// **Note**: This method is only available on platforms that support atomic operations on
3064 #[doc = concat!("[`", $s_int_type, "`].")]
3065 ///
3066 /// # Examples
3067 ///
3068 /// ```
3069 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3070 ///
3071 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
3072 ///
3073 /// assert_eq!(some_var.compare_exchange(5, 10,
3074 /// Ordering::Acquire,
3075 /// Ordering::Relaxed),
3076 /// Ok(5));
3077 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3078 ///
3079 /// assert_eq!(some_var.compare_exchange(6, 12,
3080 /// Ordering::SeqCst,
3081 /// Ordering::Acquire),
3082 /// Err(10));
3083 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
3084 /// ```
3085 ///
3086 /// # Considerations
3087 ///
3088 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3089 /// of CAS operations. In particular, a load of the value followed by a successful
3090 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3091 /// changed the value in the interim! This is usually important when the *equality* check in
3092 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3093 /// does not necessarily imply identity. This is a particularly common case for pointers, as
3094 /// a pointer holding the same address does not imply that the same object exists at that
3095 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3096 ///
3097 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3098 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3099 #[inline]
3100 #[$stable_cxchg]
3101 #[$cfg_cas]
3102 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3103 pub fn compare_exchange(&self,
3104 current: $int_type,
3105 new: $int_type,
3106 success: Ordering,
3107 failure: Ordering) -> Result<$int_type, $int_type> {
3108 // SAFETY: data races are prevented by atomic intrinsics.
3109 unsafe { atomic_compare_exchange(self.v.get(), current, new, success, failure) }
3110 }
3111
3112 /// Stores a value into the atomic integer if the current value is the same as
3113 /// the `current` value.
3114 ///
3115 #[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")]
3116 /// this function is allowed to spuriously fail even
3117 /// when the comparison succeeds, which can result in more efficient code on some
3118 /// platforms. The return value is a result indicating whether the new value was
3119 /// written and containing the previous value.
3120 ///
3121 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
3122 /// ordering of this operation. `success` describes the required ordering for the
3123 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
3124 /// `failure` describes the required ordering for the load operation that takes place when
3125 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
3126 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
3127 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3128 ///
3129 /// **Note**: This method is only available on platforms that support atomic operations on
3130 #[doc = concat!("[`", $s_int_type, "`].")]
3131 ///
3132 /// # Examples
3133 ///
3134 /// ```
3135 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3136 ///
3137 #[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")]
3138 ///
3139 /// let mut old = val.load(Ordering::Relaxed);
3140 /// loop {
3141 /// let new = old * 2;
3142 /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
3143 /// Ok(_) => break,
3144 /// Err(x) => old = x,
3145 /// }
3146 /// }
3147 /// ```
3148 ///
3149 /// # Considerations
3150 ///
3151 /// `compare_exchange` is a [compare-and-swap operation] and thus exhibits the usual downsides
3152 /// of CAS operations. In particular, a load of the value followed by a successful
3153 /// `compare_exchange` with the previous load *does not ensure* that other threads have not
3154 /// changed the value in the interim. This is usually important when the *equality* check in
3155 /// the `compare_exchange` is being used to check the *identity* of a value, but equality
3156 /// does not necessarily imply identity. This is a particularly common case for pointers, as
3157 /// a pointer holding the same address does not imply that the same object exists at that
3158 /// address! In this case, `compare_exchange` can lead to the [ABA problem].
3159 ///
3160 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3161 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3162 #[inline]
3163 #[$stable_cxchg]
3164 #[$cfg_cas]
3165 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3166 pub fn compare_exchange_weak(&self,
3167 current: $int_type,
3168 new: $int_type,
3169 success: Ordering,
3170 failure: Ordering) -> Result<$int_type, $int_type> {
3171 // SAFETY: data races are prevented by atomic intrinsics.
3172 unsafe {
3173 atomic_compare_exchange_weak(self.v.get(), current, new, success, failure)
3174 }
3175 }
3176
3177 /// Adds to the current value, returning the previous value.
3178 ///
3179 /// This operation wraps around on overflow.
3180 ///
3181 /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
3182 /// of this operation. All ordering modes are possible. Note that using
3183 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3184 /// using [`Release`] makes the load part [`Relaxed`].
3185 ///
3186 /// **Note**: This method is only available on platforms that support atomic operations on
3187 #[doc = concat!("[`", $s_int_type, "`].")]
3188 ///
3189 /// # Examples
3190 ///
3191 /// ```
3192 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3193 ///
3194 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")]
3195 /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
3196 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3197 /// ```
3198 #[inline]
3199 #[$stable]
3200 #[$cfg_cas]
3201 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3202 pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
3203 // SAFETY: data races are prevented by atomic intrinsics.
3204 unsafe { atomic_add(self.v.get(), val, order) }
3205 }
3206
3207 /// Subtracts from the current value, returning the previous value.
3208 ///
3209 /// This operation wraps around on overflow.
3210 ///
3211 /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
3212 /// of this operation. All ordering modes are possible. Note that using
3213 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3214 /// using [`Release`] makes the load part [`Relaxed`].
3215 ///
3216 /// **Note**: This method is only available on platforms that support atomic operations on
3217 #[doc = concat!("[`", $s_int_type, "`].")]
3218 ///
3219 /// # Examples
3220 ///
3221 /// ```
3222 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3223 ///
3224 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")]
3225 /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
3226 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
3227 /// ```
3228 #[inline]
3229 #[$stable]
3230 #[$cfg_cas]
3231 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3232 pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
3233 // SAFETY: data races are prevented by atomic intrinsics.
3234 unsafe { atomic_sub(self.v.get(), val, order) }
3235 }
3236
3237 /// Bitwise "and" with the current value.
3238 ///
3239 /// Performs a bitwise "and" operation on the current value and the argument `val`, and
3240 /// sets the new value to the result.
3241 ///
3242 /// Returns the previous value.
3243 ///
3244 /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
3245 /// of this operation. All ordering modes are possible. Note that using
3246 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3247 /// using [`Release`] makes the load part [`Relaxed`].
3248 ///
3249 /// **Note**: This method is only available on platforms that support atomic operations on
3250 #[doc = concat!("[`", $s_int_type, "`].")]
3251 ///
3252 /// # Examples
3253 ///
3254 /// ```
3255 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3256 ///
3257 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3258 /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
3259 /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
3260 /// ```
3261 #[inline]
3262 #[$stable]
3263 #[$cfg_cas]
3264 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3265 pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
3266 // SAFETY: data races are prevented by atomic intrinsics.
3267 unsafe { atomic_and(self.v.get(), val, order) }
3268 }
3269
3270 /// Bitwise "nand" with the current value.
3271 ///
3272 /// Performs a bitwise "nand" operation on the current value and the argument `val`, and
3273 /// sets the new value to the result.
3274 ///
3275 /// Returns the previous value.
3276 ///
3277 /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
3278 /// of this operation. All ordering modes are possible. Note that using
3279 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3280 /// using [`Release`] makes the load part [`Relaxed`].
3281 ///
3282 /// **Note**: This method is only available on platforms that support atomic operations on
3283 #[doc = concat!("[`", $s_int_type, "`].")]
3284 ///
3285 /// # Examples
3286 ///
3287 /// ```
3288 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3289 ///
3290 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")]
3291 /// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
3292 /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
3293 /// ```
3294 #[inline]
3295 #[$stable_nand]
3296 #[$cfg_cas]
3297 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3298 pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
3299 // SAFETY: data races are prevented by atomic intrinsics.
3300 unsafe { atomic_nand(self.v.get(), val, order) }
3301 }
3302
3303 /// Bitwise "or" with the current value.
3304 ///
3305 /// Performs a bitwise "or" operation on the current value and the argument `val`, and
3306 /// sets the new value to the result.
3307 ///
3308 /// Returns the previous value.
3309 ///
3310 /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
3311 /// of this operation. All ordering modes are possible. Note that using
3312 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3313 /// using [`Release`] makes the load part [`Relaxed`].
3314 ///
3315 /// **Note**: This method is only available on platforms that support atomic operations on
3316 #[doc = concat!("[`", $s_int_type, "`].")]
3317 ///
3318 /// # Examples
3319 ///
3320 /// ```
3321 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3322 ///
3323 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3324 /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
3325 /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
3326 /// ```
3327 #[inline]
3328 #[$stable]
3329 #[$cfg_cas]
3330 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3331 pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
3332 // SAFETY: data races are prevented by atomic intrinsics.
3333 unsafe { atomic_or(self.v.get(), val, order) }
3334 }
3335
3336 /// Bitwise "xor" with the current value.
3337 ///
3338 /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
3339 /// sets the new value to the result.
3340 ///
3341 /// Returns the previous value.
3342 ///
3343 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
3344 /// of this operation. All ordering modes are possible. Note that using
3345 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3346 /// using [`Release`] makes the load part [`Relaxed`].
3347 ///
3348 /// **Note**: This method is only available on platforms that support atomic operations on
3349 #[doc = concat!("[`", $s_int_type, "`].")]
3350 ///
3351 /// # Examples
3352 ///
3353 /// ```
3354 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3355 ///
3356 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
3357 /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
3358 /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
3359 /// ```
3360 #[inline]
3361 #[$stable]
3362 #[$cfg_cas]
3363 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3364 pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
3365 // SAFETY: data races are prevented by atomic intrinsics.
3366 unsafe { atomic_xor(self.v.get(), val, order) }
3367 }
3368
3369 /// Fetches the value, and applies a function to it that returns an optional
3370 /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3371 /// `Err(previous_value)`.
3372 ///
3373 /// Note: This may call the function multiple times if the value has been changed from other threads in
3374 /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3375 /// only once to the stored value.
3376 ///
3377 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3378 /// The first describes the required ordering for when the operation finally succeeds while the second
3379 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3380 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3381 /// respectively.
3382 ///
3383 /// Using [`Acquire`] as success ordering makes the store part
3384 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3385 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3386 ///
3387 /// **Note**: This method is only available on platforms that support atomic operations on
3388 #[doc = concat!("[`", $s_int_type, "`].")]
3389 ///
3390 /// # Considerations
3391 ///
3392 /// This method is not magic; it is not provided by the hardware, and does not act like a
3393 /// critical section or mutex.
3394 ///
3395 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3396 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3397 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3398 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3399 ///
3400 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3401 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3402 ///
3403 /// # Examples
3404 ///
3405 /// ```rust
3406 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3407 ///
3408 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3409 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3410 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3411 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3412 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3413 /// ```
3414 #[inline]
3415 #[stable(feature = "no_more_cas", since = "1.45.0")]
3416 #[$cfg_cas]
3417 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3418 pub fn fetch_update<F>(&self,
3419 set_order: Ordering,
3420 fetch_order: Ordering,
3421 mut f: F) -> Result<$int_type, $int_type>
3422 where F: FnMut($int_type) -> Option<$int_type> {
3423 let mut prev = self.load(fetch_order);
3424 while let Some(next) = f(prev) {
3425 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
3426 x @ Ok(_) => return x,
3427 Err(next_prev) => prev = next_prev
3428 }
3429 }
3430 Err(prev)
3431 }
3432
3433 /// Fetches the value, and applies a function to it that returns an optional
3434 /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
3435 /// `Err(previous_value)`.
3436 ///
3437 #[doc = concat!("See also: [`update`](`", stringify!($atomic_type), "::update`).")]
3438 ///
3439 /// Note: This may call the function multiple times if the value has been changed from other threads in
3440 /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
3441 /// only once to the stored value.
3442 ///
3443 /// `try_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3444 /// The first describes the required ordering for when the operation finally succeeds while the second
3445 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3446 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3447 /// respectively.
3448 ///
3449 /// Using [`Acquire`] as success ordering makes the store part
3450 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3451 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3452 ///
3453 /// **Note**: This method is only available on platforms that support atomic operations on
3454 #[doc = concat!("[`", $s_int_type, "`].")]
3455 ///
3456 /// # Considerations
3457 ///
3458 /// This method is not magic; it is not provided by the hardware, and does not act like a
3459 /// critical section or mutex.
3460 ///
3461 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3462 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3463 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3464 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3465 ///
3466 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3467 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3468 ///
3469 /// # Examples
3470 ///
3471 /// ```rust
3472 /// #![feature(atomic_try_update)]
3473 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3474 ///
3475 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3476 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
3477 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
3478 /// assert_eq!(x.try_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
3479 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3480 /// ```
3481 #[inline]
3482 #[unstable(feature = "atomic_try_update", issue = "135894")]
3483 #[$cfg_cas]
3484 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3485 pub fn try_update(
3486 &self,
3487 set_order: Ordering,
3488 fetch_order: Ordering,
3489 f: impl FnMut($int_type) -> Option<$int_type>,
3490 ) -> Result<$int_type, $int_type> {
3491 // FIXME(atomic_try_update): this is currently an unstable alias to `fetch_update`;
3492 // when stabilizing, turn `fetch_update` into a deprecated alias to `try_update`.
3493 self.fetch_update(set_order, fetch_order, f)
3494 }
3495
3496 /// Fetches the value, applies a function to it that it return a new value.
3497 /// The new value is stored and the old value is returned.
3498 ///
3499 #[doc = concat!("See also: [`try_update`](`", stringify!($atomic_type), "::try_update`).")]
3500 ///
3501 /// Note: This may call the function multiple times if the value has been changed from other threads in
3502 /// the meantime, but the function will have been applied only once to the stored value.
3503 ///
3504 /// `update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
3505 /// The first describes the required ordering for when the operation finally succeeds while the second
3506 /// describes the required ordering for loads. These correspond to the success and failure orderings of
3507 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
3508 /// respectively.
3509 ///
3510 /// Using [`Acquire`] as success ordering makes the store part
3511 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
3512 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`].
3513 ///
3514 /// **Note**: This method is only available on platforms that support atomic operations on
3515 #[doc = concat!("[`", $s_int_type, "`].")]
3516 ///
3517 /// # Considerations
3518 ///
3519 /// [CAS operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3520 /// This method is not magic; it is not provided by the hardware, and does not act like a
3521 /// critical section or mutex.
3522 ///
3523 /// It is implemented on top of an atomic [compare-and-swap operation], and thus is subject to
3524 /// the usual drawbacks of CAS operations. In particular, be careful of the [ABA problem]
3525 /// if this atomic integer is an index or more generally if knowledge of only the *bitwise value*
3526 /// of the atomic is not in and of itself sufficient to ensure any required preconditions.
3527 ///
3528 /// [ABA Problem]: https://en.wikipedia.org/wiki/ABA_problem
3529 /// [compare-and-swap operation]: https://en.wikipedia.org/wiki/Compare-and-swap
3530 ///
3531 /// # Examples
3532 ///
3533 /// ```rust
3534 /// #![feature(atomic_try_update)]
3535 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3536 ///
3537 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
3538 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 7);
3539 /// assert_eq!(x.update(Ordering::SeqCst, Ordering::SeqCst, |x| x + 1), 8);
3540 /// assert_eq!(x.load(Ordering::SeqCst), 9);
3541 /// ```
3542 #[inline]
3543 #[unstable(feature = "atomic_try_update", issue = "135894")]
3544 #[$cfg_cas]
3545 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3546 pub fn update(
3547 &self,
3548 set_order: Ordering,
3549 fetch_order: Ordering,
3550 mut f: impl FnMut($int_type) -> $int_type,
3551 ) -> $int_type {
3552 let mut prev = self.load(fetch_order);
3553 loop {
3554 match self.compare_exchange_weak(prev, f(prev), set_order, fetch_order) {
3555 Ok(x) => break x,
3556 Err(next_prev) => prev = next_prev,
3557 }
3558 }
3559 }
3560
3561 /// Maximum with the current value.
3562 ///
3563 /// Finds the maximum of the current value and the argument `val`, and
3564 /// sets the new value to the result.
3565 ///
3566 /// Returns the previous value.
3567 ///
3568 /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
3569 /// of this operation. All ordering modes are possible. Note that using
3570 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3571 /// using [`Release`] makes the load part [`Relaxed`].
3572 ///
3573 /// **Note**: This method is only available on platforms that support atomic operations on
3574 #[doc = concat!("[`", $s_int_type, "`].")]
3575 ///
3576 /// # Examples
3577 ///
3578 /// ```
3579 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3580 ///
3581 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3582 /// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
3583 /// assert_eq!(foo.load(Ordering::SeqCst), 42);
3584 /// ```
3585 ///
3586 /// If you want to obtain the maximum value in one step, you can use the following:
3587 ///
3588 /// ```
3589 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3590 ///
3591 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3592 /// let bar = 42;
3593 /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
3594 /// assert!(max_foo == 42);
3595 /// ```
3596 #[inline]
3597 #[stable(feature = "atomic_min_max", since = "1.45.0")]
3598 #[$cfg_cas]
3599 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3600 pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
3601 // SAFETY: data races are prevented by atomic intrinsics.
3602 unsafe { $max_fn(self.v.get(), val, order) }
3603 }
3604
3605 /// Minimum with the current value.
3606 ///
3607 /// Finds the minimum of the current value and the argument `val`, and
3608 /// sets the new value to the result.
3609 ///
3610 /// Returns the previous value.
3611 ///
3612 /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
3613 /// of this operation. All ordering modes are possible. Note that using
3614 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
3615 /// using [`Release`] makes the load part [`Relaxed`].
3616 ///
3617 /// **Note**: This method is only available on platforms that support atomic operations on
3618 #[doc = concat!("[`", $s_int_type, "`].")]
3619 ///
3620 /// # Examples
3621 ///
3622 /// ```
3623 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3624 ///
3625 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3626 /// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
3627 /// assert_eq!(foo.load(Ordering::Relaxed), 23);
3628 /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
3629 /// assert_eq!(foo.load(Ordering::Relaxed), 22);
3630 /// ```
3631 ///
3632 /// If you want to obtain the minimum value in one step, you can use the following:
3633 ///
3634 /// ```
3635 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
3636 ///
3637 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
3638 /// let bar = 12;
3639 /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
3640 /// assert_eq!(min_foo, 12);
3641 /// ```
3642 #[inline]
3643 #[stable(feature = "atomic_min_max", since = "1.45.0")]
3644 #[$cfg_cas]
3645 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3646 pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
3647 // SAFETY: data races are prevented by atomic intrinsics.
3648 unsafe { $min_fn(self.v.get(), val, order) }
3649 }
3650
3651 /// Returns a mutable pointer to the underlying integer.
3652 ///
3653 /// Doing non-atomic reads and writes on the resulting integer can be a data race.
3654 /// This method is mostly useful for FFI, where the function signature may use
3655 #[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")]
3656 ///
3657 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
3658 /// atomic types work with interior mutability. All modifications of an atomic change the value
3659 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
3660 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the
3661 /// requirements of the [memory model].
3662 ///
3663 /// # Examples
3664 ///
3665 /// ```ignore (extern-declaration)
3666 /// # fn main() {
3667 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
3668 ///
3669 /// extern "C" {
3670 #[doc = concat!(" fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")]
3671 /// }
3672 ///
3673 #[doc = concat!("let atomic = ", stringify!($atomic_type), "::new(1);")]
3674 ///
3675 /// // SAFETY: Safe as long as `my_atomic_op` is atomic.
3676 /// unsafe {
3677 /// my_atomic_op(atomic.as_ptr());
3678 /// }
3679 /// # }
3680 /// ```
3681 ///
3682 /// [memory model]: self#memory-model-for-atomic-accesses
3683 #[inline]
3684 #[stable(feature = "atomic_as_ptr", since = "1.70.0")]
3685 #[rustc_const_stable(feature = "atomic_as_ptr", since = "1.70.0")]
3686 #[rustc_never_returns_null_ptr]
3687 pub const fn as_ptr(&self) -> *mut $int_type {
3688 self.v.get()
3689 }
3690 }
3691 }
3692}
3693
3694#[cfg(target_has_atomic_load_store = "8")]
3695#[cfg(not(feature = "ferrocene_certified"))]
3696atomic_int! {
3697 cfg(target_has_atomic = "8"),
3698 cfg(target_has_atomic_equal_alignment = "8"),
3699 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3700 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3701 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3702 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3703 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3704 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3705 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3706 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3707 rustc_diagnostic_item = "AtomicI8",
3708 "i8",
3709 "",
3710 atomic_min, atomic_max,
3711 1,
3712 i8 AtomicI8
3713}
3714#[cfg(target_has_atomic_load_store = "8")]
3715#[cfg(not(feature = "ferrocene_certified"))]
3716atomic_int! {
3717 cfg(target_has_atomic = "8"),
3718 cfg(target_has_atomic_equal_alignment = "8"),
3719 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3720 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3721 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3722 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3723 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3724 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3725 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3726 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3727 rustc_diagnostic_item = "AtomicU8",
3728 "u8",
3729 "",
3730 atomic_umin, atomic_umax,
3731 1,
3732 u8 AtomicU8
3733}
3734#[cfg(target_has_atomic_load_store = "16")]
3735#[cfg(not(feature = "ferrocene_certified"))]
3736atomic_int! {
3737 cfg(target_has_atomic = "16"),
3738 cfg(target_has_atomic_equal_alignment = "16"),
3739 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3740 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3741 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3742 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3743 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3744 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3745 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3746 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3747 rustc_diagnostic_item = "AtomicI16",
3748 "i16",
3749 "",
3750 atomic_min, atomic_max,
3751 2,
3752 i16 AtomicI16
3753}
3754#[cfg(target_has_atomic_load_store = "16")]
3755#[cfg(not(feature = "ferrocene_certified"))]
3756atomic_int! {
3757 cfg(target_has_atomic = "16"),
3758 cfg(target_has_atomic_equal_alignment = "16"),
3759 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3760 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3761 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3762 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3763 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3764 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3765 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3766 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3767 rustc_diagnostic_item = "AtomicU16",
3768 "u16",
3769 "",
3770 atomic_umin, atomic_umax,
3771 2,
3772 u16 AtomicU16
3773}
3774#[cfg(target_has_atomic_load_store = "32")]
3775#[cfg(not(feature = "ferrocene_certified"))]
3776atomic_int! {
3777 cfg(target_has_atomic = "32"),
3778 cfg(target_has_atomic_equal_alignment = "32"),
3779 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3780 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3781 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3782 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3783 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3784 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3785 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3786 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3787 rustc_diagnostic_item = "AtomicI32",
3788 "i32",
3789 "",
3790 atomic_min, atomic_max,
3791 4,
3792 i32 AtomicI32
3793}
3794#[cfg(target_has_atomic_load_store = "32")]
3795atomic_int! {
3796 cfg(target_has_atomic = "32"),
3797 cfg(target_has_atomic_equal_alignment = "32"),
3798 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3799 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3800 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3801 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3802 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3803 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3804 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3805 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3806 rustc_diagnostic_item = "AtomicU32",
3807 "u32",
3808 "",
3809 atomic_umin, atomic_umax,
3810 4,
3811 u32 AtomicU32
3812}
3813#[cfg(target_has_atomic_load_store = "64")]
3814#[cfg(not(feature = "ferrocene_certified"))]
3815atomic_int! {
3816 cfg(target_has_atomic = "64"),
3817 cfg(target_has_atomic_equal_alignment = "64"),
3818 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3819 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3820 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3821 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3822 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3823 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3824 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3825 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3826 rustc_diagnostic_item = "AtomicI64",
3827 "i64",
3828 "",
3829 atomic_min, atomic_max,
3830 8,
3831 i64 AtomicI64
3832}
3833#[cfg(target_has_atomic_load_store = "64")]
3834#[cfg(not(feature = "ferrocene_certified"))]
3835atomic_int! {
3836 cfg(target_has_atomic = "64"),
3837 cfg(target_has_atomic_equal_alignment = "64"),
3838 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3839 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3840 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3841 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3842 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3843 stable(feature = "integer_atomics_stable", since = "1.34.0"),
3844 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
3845 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3846 rustc_diagnostic_item = "AtomicU64",
3847 "u64",
3848 "",
3849 atomic_umin, atomic_umax,
3850 8,
3851 u64 AtomicU64
3852}
3853#[cfg(target_has_atomic_load_store = "128")]
3854#[cfg(not(feature = "ferrocene_certified"))]
3855atomic_int! {
3856 cfg(target_has_atomic = "128"),
3857 cfg(target_has_atomic_equal_alignment = "128"),
3858 unstable(feature = "integer_atomics", issue = "99069"),
3859 unstable(feature = "integer_atomics", issue = "99069"),
3860 unstable(feature = "integer_atomics", issue = "99069"),
3861 unstable(feature = "integer_atomics", issue = "99069"),
3862 unstable(feature = "integer_atomics", issue = "99069"),
3863 unstable(feature = "integer_atomics", issue = "99069"),
3864 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3865 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3866 rustc_diagnostic_item = "AtomicI128",
3867 "i128",
3868 "#![feature(integer_atomics)]\n\n",
3869 atomic_min, atomic_max,
3870 16,
3871 i128 AtomicI128
3872}
3873#[cfg(target_has_atomic_load_store = "128")]
3874#[cfg(not(feature = "ferrocene_certified"))]
3875atomic_int! {
3876 cfg(target_has_atomic = "128"),
3877 cfg(target_has_atomic_equal_alignment = "128"),
3878 unstable(feature = "integer_atomics", issue = "99069"),
3879 unstable(feature = "integer_atomics", issue = "99069"),
3880 unstable(feature = "integer_atomics", issue = "99069"),
3881 unstable(feature = "integer_atomics", issue = "99069"),
3882 unstable(feature = "integer_atomics", issue = "99069"),
3883 unstable(feature = "integer_atomics", issue = "99069"),
3884 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3885 rustc_const_unstable(feature = "integer_atomics", issue = "99069"),
3886 rustc_diagnostic_item = "AtomicU128",
3887 "u128",
3888 "#![feature(integer_atomics)]\n\n",
3889 atomic_umin, atomic_umax,
3890 16,
3891 u128 AtomicU128
3892}
3893
3894#[cfg(target_has_atomic_load_store = "ptr")]
3895#[cfg(not(feature = "ferrocene_certified"))]
3896macro_rules! atomic_int_ptr_sized {
3897 ( $($target_pointer_width:literal $align:literal)* ) => { $(
3898 #[cfg(target_pointer_width = $target_pointer_width)]
3899 atomic_int! {
3900 cfg(target_has_atomic = "ptr"),
3901 cfg(target_has_atomic_equal_alignment = "ptr"),
3902 stable(feature = "rust1", since = "1.0.0"),
3903 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3904 stable(feature = "atomic_debug", since = "1.3.0"),
3905 stable(feature = "atomic_access", since = "1.15.0"),
3906 stable(feature = "atomic_from", since = "1.23.0"),
3907 stable(feature = "atomic_nand", since = "1.27.0"),
3908 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3909 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3910 rustc_diagnostic_item = "AtomicIsize",
3911 "isize",
3912 "",
3913 atomic_min, atomic_max,
3914 $align,
3915 isize AtomicIsize
3916 }
3917 #[cfg(target_pointer_width = $target_pointer_width)]
3918 atomic_int! {
3919 cfg(target_has_atomic = "ptr"),
3920 cfg(target_has_atomic_equal_alignment = "ptr"),
3921 stable(feature = "rust1", since = "1.0.0"),
3922 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
3923 stable(feature = "atomic_debug", since = "1.3.0"),
3924 stable(feature = "atomic_access", since = "1.15.0"),
3925 stable(feature = "atomic_from", since = "1.23.0"),
3926 stable(feature = "atomic_nand", since = "1.27.0"),
3927 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
3928 rustc_const_stable(feature = "const_atomic_into_inner", since = "1.79.0"),
3929 rustc_diagnostic_item = "AtomicUsize",
3930 "usize",
3931 "",
3932 atomic_umin, atomic_umax,
3933 $align,
3934 usize AtomicUsize
3935 }
3936
3937 /// An [`AtomicIsize`] initialized to `0`.
3938 #[cfg(target_pointer_width = $target_pointer_width)]
3939 #[stable(feature = "rust1", since = "1.0.0")]
3940 #[deprecated(
3941 since = "1.34.0",
3942 note = "the `new` function is now preferred",
3943 suggestion = "AtomicIsize::new(0)",
3944 )]
3945 pub const ATOMIC_ISIZE_INIT: AtomicIsize = AtomicIsize::new(0);
3946
3947 /// An [`AtomicUsize`] initialized to `0`.
3948 #[cfg(target_pointer_width = $target_pointer_width)]
3949 #[stable(feature = "rust1", since = "1.0.0")]
3950 #[deprecated(
3951 since = "1.34.0",
3952 note = "the `new` function is now preferred",
3953 suggestion = "AtomicUsize::new(0)",
3954 )]
3955 pub const ATOMIC_USIZE_INIT: AtomicUsize = AtomicUsize::new(0);
3956 )* };
3957}
3958
3959#[cfg(target_has_atomic_load_store = "ptr")]
3960#[cfg(not(feature = "ferrocene_certified"))]
3961atomic_int_ptr_sized! {
3962 "16" 2
3963 "32" 4
3964 "64" 8
3965}
3966
3967#[inline]
3968#[cfg(target_has_atomic)]
3969fn strongest_failure_ordering(order: Ordering) -> Ordering {
3970 match order {
3971 Release => Relaxed,
3972 Relaxed => Relaxed,
3973 SeqCst => SeqCst,
3974 Acquire => Acquire,
3975 AcqRel => Acquire,
3976 }
3977}
3978
3979#[inline]
3980#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3981unsafe fn atomic_store<T: Copy>(dst: *mut T, val: T, order: Ordering) {
3982 // SAFETY: the caller must uphold the safety contract for `atomic_store`.
3983 unsafe {
3984 match order {
3985 Relaxed => intrinsics::atomic_store::<T, { AO::Relaxed }>(dst, val),
3986 Release => intrinsics::atomic_store::<T, { AO::Release }>(dst, val),
3987 SeqCst => intrinsics::atomic_store::<T, { AO::SeqCst }>(dst, val),
3988 Acquire => panic!("there is no such thing as an acquire store"),
3989 AcqRel => panic!("there is no such thing as an acquire-release store"),
3990 }
3991 }
3992}
3993
3994#[inline]
3995#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
3996unsafe fn atomic_load<T: Copy>(dst: *const T, order: Ordering) -> T {
3997 // SAFETY: the caller must uphold the safety contract for `atomic_load`.
3998 unsafe {
3999 match order {
4000 Relaxed => intrinsics::atomic_load::<T, { AO::Relaxed }>(dst),
4001 Acquire => intrinsics::atomic_load::<T, { AO::Acquire }>(dst),
4002 SeqCst => intrinsics::atomic_load::<T, { AO::SeqCst }>(dst),
4003 Release => panic!("there is no such thing as a release load"),
4004 AcqRel => panic!("there is no such thing as an acquire-release load"),
4005 }
4006 }
4007}
4008
4009#[inline]
4010#[cfg(target_has_atomic)]
4011#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4012unsafe fn atomic_swap<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4013 // SAFETY: the caller must uphold the safety contract for `atomic_swap`.
4014 unsafe {
4015 match order {
4016 Relaxed => intrinsics::atomic_xchg::<T, { AO::Relaxed }>(dst, val),
4017 Acquire => intrinsics::atomic_xchg::<T, { AO::Acquire }>(dst, val),
4018 Release => intrinsics::atomic_xchg::<T, { AO::Release }>(dst, val),
4019 AcqRel => intrinsics::atomic_xchg::<T, { AO::AcqRel }>(dst, val),
4020 SeqCst => intrinsics::atomic_xchg::<T, { AO::SeqCst }>(dst, val),
4021 }
4022 }
4023}
4024
4025/// Returns the previous value (like __sync_fetch_and_add).
4026#[inline]
4027#[cfg(target_has_atomic)]
4028#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4029unsafe fn atomic_add<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4030 // SAFETY: the caller must uphold the safety contract for `atomic_add`.
4031 unsafe {
4032 match order {
4033 Relaxed => intrinsics::atomic_xadd::<T, U, { AO::Relaxed }>(dst, val),
4034 Acquire => intrinsics::atomic_xadd::<T, U, { AO::Acquire }>(dst, val),
4035 Release => intrinsics::atomic_xadd::<T, U, { AO::Release }>(dst, val),
4036 AcqRel => intrinsics::atomic_xadd::<T, U, { AO::AcqRel }>(dst, val),
4037 SeqCst => intrinsics::atomic_xadd::<T, U, { AO::SeqCst }>(dst, val),
4038 }
4039 }
4040}
4041
4042/// Returns the previous value (like __sync_fetch_and_sub).
4043#[inline]
4044#[cfg(target_has_atomic)]
4045#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4046unsafe fn atomic_sub<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4047 // SAFETY: the caller must uphold the safety contract for `atomic_sub`.
4048 unsafe {
4049 match order {
4050 Relaxed => intrinsics::atomic_xsub::<T, U, { AO::Relaxed }>(dst, val),
4051 Acquire => intrinsics::atomic_xsub::<T, U, { AO::Acquire }>(dst, val),
4052 Release => intrinsics::atomic_xsub::<T, U, { AO::Release }>(dst, val),
4053 AcqRel => intrinsics::atomic_xsub::<T, U, { AO::AcqRel }>(dst, val),
4054 SeqCst => intrinsics::atomic_xsub::<T, U, { AO::SeqCst }>(dst, val),
4055 }
4056 }
4057}
4058
4059/// Publicly exposed for stdarch; nobody else should use this.
4060#[inline]
4061#[cfg(target_has_atomic)]
4062#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4063#[unstable(feature = "core_intrinsics", issue = "none")]
4064#[doc(hidden)]
4065pub unsafe fn atomic_compare_exchange<T: Copy>(
4066 dst: *mut T,
4067 old: T,
4068 new: T,
4069 success: Ordering,
4070 failure: Ordering,
4071) -> Result<T, T> {
4072 // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`.
4073 let (val, ok) = unsafe {
4074 match (success, failure) {
4075 (Relaxed, Relaxed) => {
4076 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4077 }
4078 (Relaxed, Acquire) => {
4079 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4080 }
4081 (Relaxed, SeqCst) => {
4082 intrinsics::atomic_cxchg::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4083 }
4084 (Acquire, Relaxed) => {
4085 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4086 }
4087 (Acquire, Acquire) => {
4088 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4089 }
4090 (Acquire, SeqCst) => {
4091 intrinsics::atomic_cxchg::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4092 }
4093 (Release, Relaxed) => {
4094 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4095 }
4096 (Release, Acquire) => {
4097 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4098 }
4099 (Release, SeqCst) => {
4100 intrinsics::atomic_cxchg::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4101 }
4102 (AcqRel, Relaxed) => {
4103 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4104 }
4105 (AcqRel, Acquire) => {
4106 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4107 }
4108 (AcqRel, SeqCst) => {
4109 intrinsics::atomic_cxchg::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4110 }
4111 (SeqCst, Relaxed) => {
4112 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4113 }
4114 (SeqCst, Acquire) => {
4115 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4116 }
4117 (SeqCst, SeqCst) => {
4118 intrinsics::atomic_cxchg::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4119 }
4120 (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
4121 (_, Release) => panic!("there is no such thing as a release failure ordering"),
4122 }
4123 };
4124 if ok { Ok(val) } else { Err(val) }
4125}
4126
4127#[inline]
4128#[cfg(target_has_atomic)]
4129#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4130unsafe fn atomic_compare_exchange_weak<T: Copy>(
4131 dst: *mut T,
4132 old: T,
4133 new: T,
4134 success: Ordering,
4135 failure: Ordering,
4136) -> Result<T, T> {
4137 // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`.
4138 let (val, ok) = unsafe {
4139 match (success, failure) {
4140 (Relaxed, Relaxed) => {
4141 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Relaxed }>(dst, old, new)
4142 }
4143 (Relaxed, Acquire) => {
4144 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::Acquire }>(dst, old, new)
4145 }
4146 (Relaxed, SeqCst) => {
4147 intrinsics::atomic_cxchgweak::<T, { AO::Relaxed }, { AO::SeqCst }>(dst, old, new)
4148 }
4149 (Acquire, Relaxed) => {
4150 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Relaxed }>(dst, old, new)
4151 }
4152 (Acquire, Acquire) => {
4153 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::Acquire }>(dst, old, new)
4154 }
4155 (Acquire, SeqCst) => {
4156 intrinsics::atomic_cxchgweak::<T, { AO::Acquire }, { AO::SeqCst }>(dst, old, new)
4157 }
4158 (Release, Relaxed) => {
4159 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Relaxed }>(dst, old, new)
4160 }
4161 (Release, Acquire) => {
4162 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::Acquire }>(dst, old, new)
4163 }
4164 (Release, SeqCst) => {
4165 intrinsics::atomic_cxchgweak::<T, { AO::Release }, { AO::SeqCst }>(dst, old, new)
4166 }
4167 (AcqRel, Relaxed) => {
4168 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Relaxed }>(dst, old, new)
4169 }
4170 (AcqRel, Acquire) => {
4171 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::Acquire }>(dst, old, new)
4172 }
4173 (AcqRel, SeqCst) => {
4174 intrinsics::atomic_cxchgweak::<T, { AO::AcqRel }, { AO::SeqCst }>(dst, old, new)
4175 }
4176 (SeqCst, Relaxed) => {
4177 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Relaxed }>(dst, old, new)
4178 }
4179 (SeqCst, Acquire) => {
4180 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::Acquire }>(dst, old, new)
4181 }
4182 (SeqCst, SeqCst) => {
4183 intrinsics::atomic_cxchgweak::<T, { AO::SeqCst }, { AO::SeqCst }>(dst, old, new)
4184 }
4185 (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
4186 (_, Release) => panic!("there is no such thing as a release failure ordering"),
4187 }
4188 };
4189 if ok { Ok(val) } else { Err(val) }
4190}
4191
4192#[inline]
4193#[cfg(target_has_atomic)]
4194#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4195unsafe fn atomic_and<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4196 // SAFETY: the caller must uphold the safety contract for `atomic_and`
4197 unsafe {
4198 match order {
4199 Relaxed => intrinsics::atomic_and::<T, U, { AO::Relaxed }>(dst, val),
4200 Acquire => intrinsics::atomic_and::<T, U, { AO::Acquire }>(dst, val),
4201 Release => intrinsics::atomic_and::<T, U, { AO::Release }>(dst, val),
4202 AcqRel => intrinsics::atomic_and::<T, U, { AO::AcqRel }>(dst, val),
4203 SeqCst => intrinsics::atomic_and::<T, U, { AO::SeqCst }>(dst, val),
4204 }
4205 }
4206}
4207
4208#[inline]
4209#[cfg(target_has_atomic)]
4210#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4211unsafe fn atomic_nand<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4212 // SAFETY: the caller must uphold the safety contract for `atomic_nand`
4213 unsafe {
4214 match order {
4215 Relaxed => intrinsics::atomic_nand::<T, U, { AO::Relaxed }>(dst, val),
4216 Acquire => intrinsics::atomic_nand::<T, U, { AO::Acquire }>(dst, val),
4217 Release => intrinsics::atomic_nand::<T, U, { AO::Release }>(dst, val),
4218 AcqRel => intrinsics::atomic_nand::<T, U, { AO::AcqRel }>(dst, val),
4219 SeqCst => intrinsics::atomic_nand::<T, U, { AO::SeqCst }>(dst, val),
4220 }
4221 }
4222}
4223
4224#[inline]
4225#[cfg(target_has_atomic)]
4226#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4227unsafe fn atomic_or<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4228 // SAFETY: the caller must uphold the safety contract for `atomic_or`
4229 unsafe {
4230 match order {
4231 SeqCst => intrinsics::atomic_or::<T, U, { AO::SeqCst }>(dst, val),
4232 Acquire => intrinsics::atomic_or::<T, U, { AO::Acquire }>(dst, val),
4233 Release => intrinsics::atomic_or::<T, U, { AO::Release }>(dst, val),
4234 AcqRel => intrinsics::atomic_or::<T, U, { AO::AcqRel }>(dst, val),
4235 Relaxed => intrinsics::atomic_or::<T, U, { AO::Relaxed }>(dst, val),
4236 }
4237 }
4238}
4239
4240#[inline]
4241#[cfg(target_has_atomic)]
4242#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4243unsafe fn atomic_xor<T: Copy, U: Copy>(dst: *mut T, val: U, order: Ordering) -> T {
4244 // SAFETY: the caller must uphold the safety contract for `atomic_xor`
4245 unsafe {
4246 match order {
4247 SeqCst => intrinsics::atomic_xor::<T, U, { AO::SeqCst }>(dst, val),
4248 Acquire => intrinsics::atomic_xor::<T, U, { AO::Acquire }>(dst, val),
4249 Release => intrinsics::atomic_xor::<T, U, { AO::Release }>(dst, val),
4250 AcqRel => intrinsics::atomic_xor::<T, U, { AO::AcqRel }>(dst, val),
4251 Relaxed => intrinsics::atomic_xor::<T, U, { AO::Relaxed }>(dst, val),
4252 }
4253 }
4254}
4255
4256/// Updates `*dst` to the max value of `val` and the old value (signed comparison)
4257#[inline]
4258#[cfg(target_has_atomic)]
4259#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4260#[cfg(not(feature = "ferrocene_certified"))]
4261unsafe fn atomic_max<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4262 // SAFETY: the caller must uphold the safety contract for `atomic_max`
4263 unsafe {
4264 match order {
4265 Relaxed => intrinsics::atomic_max::<T, { AO::Relaxed }>(dst, val),
4266 Acquire => intrinsics::atomic_max::<T, { AO::Acquire }>(dst, val),
4267 Release => intrinsics::atomic_max::<T, { AO::Release }>(dst, val),
4268 AcqRel => intrinsics::atomic_max::<T, { AO::AcqRel }>(dst, val),
4269 SeqCst => intrinsics::atomic_max::<T, { AO::SeqCst }>(dst, val),
4270 }
4271 }
4272}
4273
4274/// Updates `*dst` to the min value of `val` and the old value (signed comparison)
4275#[inline]
4276#[cfg(target_has_atomic)]
4277#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4278#[cfg(not(feature = "ferrocene_certified"))]
4279unsafe fn atomic_min<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4280 // SAFETY: the caller must uphold the safety contract for `atomic_min`
4281 unsafe {
4282 match order {
4283 Relaxed => intrinsics::atomic_min::<T, { AO::Relaxed }>(dst, val),
4284 Acquire => intrinsics::atomic_min::<T, { AO::Acquire }>(dst, val),
4285 Release => intrinsics::atomic_min::<T, { AO::Release }>(dst, val),
4286 AcqRel => intrinsics::atomic_min::<T, { AO::AcqRel }>(dst, val),
4287 SeqCst => intrinsics::atomic_min::<T, { AO::SeqCst }>(dst, val),
4288 }
4289 }
4290}
4291
4292/// Updates `*dst` to the max value of `val` and the old value (unsigned comparison)
4293#[inline]
4294#[cfg(target_has_atomic)]
4295#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4296unsafe fn atomic_umax<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4297 // SAFETY: the caller must uphold the safety contract for `atomic_umax`
4298 unsafe {
4299 match order {
4300 Relaxed => intrinsics::atomic_umax::<T, { AO::Relaxed }>(dst, val),
4301 Acquire => intrinsics::atomic_umax::<T, { AO::Acquire }>(dst, val),
4302 Release => intrinsics::atomic_umax::<T, { AO::Release }>(dst, val),
4303 AcqRel => intrinsics::atomic_umax::<T, { AO::AcqRel }>(dst, val),
4304 SeqCst => intrinsics::atomic_umax::<T, { AO::SeqCst }>(dst, val),
4305 }
4306 }
4307}
4308
4309/// Updates `*dst` to the min value of `val` and the old value (unsigned comparison)
4310#[inline]
4311#[cfg(target_has_atomic)]
4312#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4313unsafe fn atomic_umin<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
4314 // SAFETY: the caller must uphold the safety contract for `atomic_umin`
4315 unsafe {
4316 match order {
4317 Relaxed => intrinsics::atomic_umin::<T, { AO::Relaxed }>(dst, val),
4318 Acquire => intrinsics::atomic_umin::<T, { AO::Acquire }>(dst, val),
4319 Release => intrinsics::atomic_umin::<T, { AO::Release }>(dst, val),
4320 AcqRel => intrinsics::atomic_umin::<T, { AO::AcqRel }>(dst, val),
4321 SeqCst => intrinsics::atomic_umin::<T, { AO::SeqCst }>(dst, val),
4322 }
4323 }
4324}
4325
4326/// An atomic fence.
4327///
4328/// Fences create synchronization between themselves and atomic operations or fences in other
4329/// threads. To achieve this, a fence prevents the compiler and CPU from reordering certain types of
4330/// memory operations around it.
4331///
4332/// A fence 'A' which has (at least) [`Release`] ordering semantics, synchronizes
4333/// with a fence 'B' with (at least) [`Acquire`] semantics, if and only if there
4334/// exist operations X and Y, both operating on some atomic object 'm' such
4335/// that A is sequenced before X, Y is sequenced before B and Y observes
4336/// the change to m. This provides a happens-before dependence between A and B.
4337///
4338/// ```text
4339/// Thread 1 Thread 2
4340///
4341/// fence(Release); A --------------
4342/// m.store(3, Relaxed); X --------- |
4343/// | |
4344/// | |
4345/// -------------> Y if m.load(Relaxed) == 3 {
4346/// |-------> B fence(Acquire);
4347/// ...
4348/// }
4349/// ```
4350///
4351/// Note that in the example above, it is crucial that the accesses to `m` are atomic. Fences cannot
4352/// be used to establish synchronization among non-atomic accesses in different threads. However,
4353/// thanks to the happens-before relationship between A and B, any non-atomic accesses that
4354/// happen-before A are now also properly synchronized with any non-atomic accesses that
4355/// happen-after B.
4356///
4357/// Atomic operations with [`Release`] or [`Acquire`] semantics can also synchronize
4358/// with a fence.
4359///
4360/// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`]
4361/// and [`Release`] semantics, participates in the global program order of the
4362/// other [`SeqCst`] operations and/or fences.
4363///
4364/// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings.
4365///
4366/// # Panics
4367///
4368/// Panics if `order` is [`Relaxed`].
4369///
4370/// # Examples
4371///
4372/// ```
4373/// use std::sync::atomic::AtomicBool;
4374/// use std::sync::atomic::fence;
4375/// use std::sync::atomic::Ordering;
4376///
4377/// // A mutual exclusion primitive based on spinlock.
4378/// pub struct Mutex {
4379/// flag: AtomicBool,
4380/// }
4381///
4382/// impl Mutex {
4383/// pub fn new() -> Mutex {
4384/// Mutex {
4385/// flag: AtomicBool::new(false),
4386/// }
4387/// }
4388///
4389/// pub fn lock(&self) {
4390/// // Wait until the old value is `false`.
4391/// while self
4392/// .flag
4393/// .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
4394/// .is_err()
4395/// {}
4396/// // This fence synchronizes-with store in `unlock`.
4397/// fence(Ordering::Acquire);
4398/// }
4399///
4400/// pub fn unlock(&self) {
4401/// self.flag.store(false, Ordering::Release);
4402/// }
4403/// }
4404/// ```
4405#[inline]
4406#[stable(feature = "rust1", since = "1.0.0")]
4407#[rustc_diagnostic_item = "fence"]
4408#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4409#[cfg(not(feature = "ferrocene_certified"))]
4410pub fn fence(order: Ordering) {
4411 // SAFETY: using an atomic fence is safe.
4412 unsafe {
4413 match order {
4414 Acquire => intrinsics::atomic_fence::<{ AO::Acquire }>(),
4415 Release => intrinsics::atomic_fence::<{ AO::Release }>(),
4416 AcqRel => intrinsics::atomic_fence::<{ AO::AcqRel }>(),
4417 SeqCst => intrinsics::atomic_fence::<{ AO::SeqCst }>(),
4418 Relaxed => panic!("there is no such thing as a relaxed fence"),
4419 }
4420 }
4421}
4422
4423/// A "compiler-only" atomic fence.
4424///
4425/// Like [`fence`], this function establishes synchronization with other atomic operations and
4426/// fences. However, unlike [`fence`], `compiler_fence` only establishes synchronization with
4427/// operations *in the same thread*. This may at first sound rather useless, since code within a
4428/// thread is typically already totally ordered and does not need any further synchronization.
4429/// However, there are cases where code can run on the same thread without being ordered:
4430/// - The most common case is that of a *signal handler*: a signal handler runs in the same thread
4431/// as the code it interrupted, but it is not ordered with respect to that code. `compiler_fence`
4432/// can be used to establish synchronization between a thread and its signal handler, the same way
4433/// that `fence` can be used to establish synchronization across threads.
4434/// - Similar situations can arise in embedded programming with interrupt handlers, or in custom
4435/// implementations of preemptive green threads. In general, `compiler_fence` can establish
4436/// synchronization with code that is guaranteed to run on the same hardware CPU.
4437///
4438/// See [`fence`] for how a fence can be used to achieve synchronization. Note that just like
4439/// [`fence`], synchronization still requires atomic operations to be used in both threads -- it is
4440/// not possible to perform synchronization entirely with fences and non-atomic operations.
4441///
4442/// `compiler_fence` does not emit any machine code, but restricts the kinds of memory re-ordering
4443/// the compiler is allowed to do. `compiler_fence` corresponds to [`atomic_signal_fence`] in C and
4444/// C++.
4445///
4446/// [`atomic_signal_fence`]: https://en.cppreference.com/w/cpp/atomic/atomic_signal_fence
4447///
4448/// # Panics
4449///
4450/// Panics if `order` is [`Relaxed`].
4451///
4452/// # Examples
4453///
4454/// Without the two `compiler_fence` calls, the read of `IMPORTANT_VARIABLE` in `signal_handler`
4455/// is *undefined behavior* due to a data race, despite everything happening in a single thread.
4456/// This is because the signal handler is considered to run concurrently with its associated
4457/// thread, and explicit synchronization is required to pass data between a thread and its
4458/// signal handler. The code below uses two `compiler_fence` calls to establish the usual
4459/// release-acquire synchronization pattern (see [`fence`] for an image).
4460///
4461/// ```
4462/// use std::sync::atomic::AtomicBool;
4463/// use std::sync::atomic::Ordering;
4464/// use std::sync::atomic::compiler_fence;
4465///
4466/// static mut IMPORTANT_VARIABLE: usize = 0;
4467/// static IS_READY: AtomicBool = AtomicBool::new(false);
4468///
4469/// fn main() {
4470/// unsafe { IMPORTANT_VARIABLE = 42 };
4471/// // Marks earlier writes as being released with future relaxed stores.
4472/// compiler_fence(Ordering::Release);
4473/// IS_READY.store(true, Ordering::Relaxed);
4474/// }
4475///
4476/// fn signal_handler() {
4477/// if IS_READY.load(Ordering::Relaxed) {
4478/// // Acquires writes that were released with relaxed stores that we read from.
4479/// compiler_fence(Ordering::Acquire);
4480/// assert_eq!(unsafe { IMPORTANT_VARIABLE }, 42);
4481/// }
4482/// }
4483/// ```
4484#[inline]
4485#[stable(feature = "compiler_fences", since = "1.21.0")]
4486#[rustc_diagnostic_item = "compiler_fence"]
4487#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
4488#[cfg(not(feature = "ferrocene_certified"))]
4489pub fn compiler_fence(order: Ordering) {
4490 // SAFETY: using an atomic fence is safe.
4491 unsafe {
4492 match order {
4493 Acquire => intrinsics::atomic_singlethreadfence::<{ AO::Acquire }>(),
4494 Release => intrinsics::atomic_singlethreadfence::<{ AO::Release }>(),
4495 AcqRel => intrinsics::atomic_singlethreadfence::<{ AO::AcqRel }>(),
4496 SeqCst => intrinsics::atomic_singlethreadfence::<{ AO::SeqCst }>(),
4497 Relaxed => panic!("there is no such thing as a relaxed fence"),
4498 }
4499 }
4500}
4501
4502#[cfg(target_has_atomic_load_store = "8")]
4503#[stable(feature = "atomic_debug", since = "1.3.0")]
4504#[cfg(not(feature = "ferrocene_certified"))]
4505impl fmt::Debug for AtomicBool {
4506 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4507 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4508 }
4509}
4510
4511#[cfg(target_has_atomic_load_store = "ptr")]
4512#[stable(feature = "atomic_debug", since = "1.3.0")]
4513#[cfg(not(feature = "ferrocene_certified"))]
4514impl<T> fmt::Debug for AtomicPtr<T> {
4515 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4516 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
4517 }
4518}
4519
4520#[cfg(target_has_atomic_load_store = "ptr")]
4521#[stable(feature = "atomic_pointer", since = "1.24.0")]
4522#[cfg(not(feature = "ferrocene_certified"))]
4523impl<T> fmt::Pointer for AtomicPtr<T> {
4524 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4525 fmt::Pointer::fmt(&self.load(Ordering::Relaxed), f)
4526 }
4527}
4528
4529/// Signals the processor that it is inside a busy-wait spin-loop ("spin lock").
4530///
4531/// This function is deprecated in favor of [`hint::spin_loop`].
4532///
4533/// [`hint::spin_loop`]: crate::hint::spin_loop
4534#[inline]
4535#[stable(feature = "spin_loop_hint", since = "1.24.0")]
4536#[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")]
4537#[cfg(not(feature = "ferrocene_certified"))]
4538pub fn spin_loop_hint() {
4539 spin_loop()
4540}