3 //! Atomic types provide primitive shared-memory communication between
4 //! threads, and are the building blocks of other concurrent
7 //! Rust atomics currently follow the same rules as [C++20 atomics][cpp], specifically `atomic_ref`.
8 //! Basically, creating a *shared reference* to one of the Rust atomic types corresponds to creating
9 //! an `atomic_ref` in C++; the `atomic_ref` is destroyed when the lifetime of the shared reference
10 //! ends. (A Rust atomic type that is exclusively owned or behind a mutable reference does *not*
11 //! correspond to an "atomic object" in C++, since it can be accessed via non-atomic operations.)
13 //! This module defines atomic versions of a select number of primitive
14 //! types, including [`AtomicBool`], [`AtomicIsize`], [`AtomicUsize`],
15 //! [`AtomicI8`], [`AtomicU16`], etc.
16 //! Atomic types present operations that, when used correctly, synchronize
17 //! updates between threads.
19 //! Each method takes an [`Ordering`] which represents the strength of
20 //! the memory barrier for that operation. These orderings are the
21 //! same as the [C++20 atomic orderings][1]. For more information see the [nomicon][2].
23 //! [cpp]: https://en.cppreference.com/w/cpp/atomic
24 //! [1]: https://en.cppreference.com/w/cpp/atomic/memory_order
25 //! [2]: ../../../nomicon/atomics.html
27 //! Atomic variables are safe to share between threads (they implement [`Sync`])
28 //! but they do not themselves provide the mechanism for sharing and follow the
29 //! [threading model](../../../std/thread/index.html#the-threading-model) of Rust.
30 //! The most common way to share an atomic variable is to put it into an [`Arc`][arc] (an
31 //! atomically-reference-counted shared pointer).
33 //! [arc]: ../../../std/sync/struct.Arc.html
35 //! Atomic types may be stored in static variables, initialized using
36 //! the constant initializers like [`AtomicBool::new`]. Atomic statics
37 //! are often used for lazy global initialization.
41 //! All atomic types in this module are guaranteed to be [lock-free] if they're
42 //! available. This means they don't internally acquire a global mutex. Atomic
43 //! types and operations are not guaranteed to be wait-free. This means that
44 //! operations like `fetch_or` may be implemented with a compare-and-swap loop.
46 //! Atomic operations may be implemented at the instruction layer with
47 //! larger-size atomics. For example some platforms use 4-byte atomic
48 //! instructions to implement `AtomicI8`. Note that this emulation should not
49 //! have an impact on correctness of code, it's just something to be aware of.
51 //! The atomic types in this module might not be available on all platforms. The
52 //! atomic types here are all widely available, however, and can generally be
53 //! relied upon existing. Some notable exceptions are:
55 //! * PowerPC and MIPS platforms with 32-bit pointers do not have `AtomicU64` or
56 //! `AtomicI64` types.
57 //! * ARM platforms like `armv5te` that aren't for Linux only provide `load`
58 //! and `store` operations, and do not support Compare and Swap (CAS)
59 //! operations, such as `swap`, `fetch_add`, etc. Additionally on Linux,
60 //! these CAS operations are implemented via [operating system support], which
61 //! may come with a performance penalty.
62 //! * ARM targets with `thumbv6m` only provide `load` and `store` operations,
63 //! and do not support Compare and Swap (CAS) operations, such as `swap`,
66 //! [operating system support]: https://www.kernel.org/doc/Documentation/arm/kernel_user_helpers.txt
68 //! Note that future platforms may be added that also do not have support for
69 //! some atomic operations. Maximally portable code will want to be careful
70 //! about which atomic types are used. `AtomicUsize` and `AtomicIsize` are
71 //! generally the most portable, but even then they're not available everywhere.
72 //! For reference, the `std` library requires `AtomicBool`s and pointer-sized atomics, although
75 //! The `#[cfg(target_has_atomic)]` attribute can be used to conditionally
76 //! compile based on the target's supported bit widths. It is a key-value
77 //! option set for each supported size, with values "8", "16", "32", "64",
78 //! "128", and "ptr" for pointer-sized atomics.
80 //! [lock-free]: https://en.wikipedia.org/wiki/Non-blocking_algorithm
84 //! A simple spinlock:
87 //! use std::sync::Arc;
88 //! use std::sync::atomic::{AtomicUsize, Ordering};
89 //! use std::{hint, thread};
92 //! let spinlock = Arc::new(AtomicUsize::new(1));
94 //! let spinlock_clone = Arc::clone(&spinlock);
95 //! let thread = thread::spawn(move|| {
96 //! spinlock_clone.store(0, Ordering::SeqCst);
99 //! // Wait for the other thread to release the lock
100 //! while spinlock.load(Ordering::SeqCst) != 0 {
101 //! hint::spin_loop();
104 //! if let Err(panic) = thread.join() {
105 //! println!("Thread had an error: {panic:?}");
110 //! Keep a global count of live threads:
113 //! use std::sync::atomic::{AtomicUsize, Ordering};
115 //! static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0);
117 //! let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::SeqCst);
118 //! println!("live threads: {}", old_thread_count + 1);
121 #![stable(feature = "rust1", since = "1.0.0")]
122 #![cfg_attr(not(target_has_atomic_load_store = "8"), allow(dead_code))]
123 #![cfg_attr(not(target_has_atomic_load_store = "8"), allow(unused_imports))]
124 #![rustc_diagnostic_item = "atomic_mod"]
126 use self::Ordering::*;
128 use crate::cell::UnsafeCell;
130 use crate::intrinsics;
132 use crate::hint::spin_loop;
134 /// A boolean type which can be safely shared between threads.
136 /// This type has the same in-memory representation as a [`bool`].
138 /// **Note**: This type is only available on platforms that support atomic
139 /// loads and stores of `u8`.
140 #[cfg(target_has_atomic_load_store = "8")]
141 #[stable(feature = "rust1", since = "1.0.0")]
142 #[rustc_diagnostic_item = "AtomicBool"]
144 pub struct AtomicBool {
148 #[cfg(target_has_atomic_load_store = "8")]
149 #[stable(feature = "rust1", since = "1.0.0")]
150 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
151 impl const Default for AtomicBool {
152 /// Creates an `AtomicBool` initialized to `false`.
154 fn default() -> Self {
159 // Send is implicitly implemented for AtomicBool.
160 #[cfg(target_has_atomic_load_store = "8")]
161 #[stable(feature = "rust1", since = "1.0.0")]
162 unsafe impl Sync for AtomicBool {}
164 /// A raw pointer type which can be safely shared between threads.
166 /// This type has the same in-memory representation as a `*mut T`.
168 /// **Note**: This type is only available on platforms that support atomic
169 /// loads and stores of pointers. Its size depends on the target pointer's size.
170 #[cfg(target_has_atomic_load_store = "ptr")]
171 #[stable(feature = "rust1", since = "1.0.0")]
172 #[cfg_attr(not(test), rustc_diagnostic_item = "AtomicPtr")]
173 #[cfg_attr(target_pointer_width = "16", repr(C, align(2)))]
174 #[cfg_attr(target_pointer_width = "32", repr(C, align(4)))]
175 #[cfg_attr(target_pointer_width = "64", repr(C, align(8)))]
176 pub struct AtomicPtr<T> {
177 p: UnsafeCell<*mut T>,
180 #[cfg(target_has_atomic_load_store = "ptr")]
181 #[stable(feature = "rust1", since = "1.0.0")]
182 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
183 impl<T> const Default for AtomicPtr<T> {
184 /// Creates a null `AtomicPtr<T>`.
185 fn default() -> AtomicPtr<T> {
186 AtomicPtr::new(crate::ptr::null_mut())
190 #[cfg(target_has_atomic_load_store = "ptr")]
191 #[stable(feature = "rust1", since = "1.0.0")]
192 unsafe impl<T> Send for AtomicPtr<T> {}
193 #[cfg(target_has_atomic_load_store = "ptr")]
194 #[stable(feature = "rust1", since = "1.0.0")]
195 unsafe impl<T> Sync for AtomicPtr<T> {}
197 /// Atomic memory orderings
199 /// Memory orderings specify the way atomic operations synchronize memory.
200 /// In its weakest [`Ordering::Relaxed`], only the memory directly touched by the
201 /// operation is synchronized. On the other hand, a store-load pair of [`Ordering::SeqCst`]
202 /// operations synchronize other memory while additionally preserving a total order of such
203 /// operations across all threads.
205 /// Rust's memory orderings are [the same as those of
206 /// C++20](https://en.cppreference.com/w/cpp/atomic/memory_order).
208 /// For more information see the [nomicon].
210 /// [nomicon]: ../../../nomicon/atomics.html
211 #[stable(feature = "rust1", since = "1.0.0")]
212 #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
214 #[rustc_diagnostic_item = "Ordering"]
216 /// No ordering constraints, only atomic operations.
218 /// Corresponds to [`memory_order_relaxed`] in C++20.
220 /// [`memory_order_relaxed`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Relaxed_ordering
221 #[stable(feature = "rust1", since = "1.0.0")]
223 /// When coupled with a store, all previous operations become ordered
224 /// before any load of this value with [`Acquire`] (or stronger) ordering.
225 /// In particular, all previous writes become visible to all threads
226 /// that perform an [`Acquire`] (or stronger) load of this value.
228 /// Notice that using this ordering for an operation that combines loads
229 /// and stores leads to a [`Relaxed`] load operation!
231 /// This ordering is only applicable for operations that can perform a store.
233 /// Corresponds to [`memory_order_release`] in C++20.
235 /// [`memory_order_release`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
236 #[stable(feature = "rust1", since = "1.0.0")]
238 /// When coupled with a load, if the loaded value was written by a store operation with
239 /// [`Release`] (or stronger) ordering, then all subsequent operations
240 /// become ordered after that store. In particular, all subsequent loads will see data
241 /// written before the store.
243 /// Notice that using this ordering for an operation that combines loads
244 /// and stores leads to a [`Relaxed`] store operation!
246 /// This ordering is only applicable for operations that can perform a load.
248 /// Corresponds to [`memory_order_acquire`] in C++20.
250 /// [`memory_order_acquire`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
251 #[stable(feature = "rust1", since = "1.0.0")]
253 /// Has the effects of both [`Acquire`] and [`Release`] together:
254 /// For loads it uses [`Acquire`] ordering. For stores it uses the [`Release`] ordering.
256 /// Notice that in the case of `compare_and_swap`, it is possible that the operation ends up
257 /// not performing any store and hence it has just [`Acquire`] ordering. However,
258 /// `AcqRel` will never perform [`Relaxed`] accesses.
260 /// This ordering is only applicable for operations that combine both loads and stores.
262 /// Corresponds to [`memory_order_acq_rel`] in C++20.
264 /// [`memory_order_acq_rel`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Release-Acquire_ordering
265 #[stable(feature = "rust1", since = "1.0.0")]
267 /// Like [`Acquire`]/[`Release`]/[`AcqRel`] (for load, store, and load-with-store
268 /// operations, respectively) with the additional guarantee that all threads see all
269 /// sequentially consistent operations in the same order.
271 /// Corresponds to [`memory_order_seq_cst`] in C++20.
273 /// [`memory_order_seq_cst`]: https://en.cppreference.com/w/cpp/atomic/memory_order#Sequentially-consistent_ordering
274 #[stable(feature = "rust1", since = "1.0.0")]
278 /// An [`AtomicBool`] initialized to `false`.
279 #[cfg(target_has_atomic_load_store = "8")]
280 #[stable(feature = "rust1", since = "1.0.0")]
283 note = "the `new` function is now preferred",
284 suggestion = "AtomicBool::new(false)"
286 pub const ATOMIC_BOOL_INIT: AtomicBool = AtomicBool::new(false);
288 #[cfg(target_has_atomic_load_store = "8")]
290 /// Creates a new `AtomicBool`.
295 /// use std::sync::atomic::AtomicBool;
297 /// let atomic_true = AtomicBool::new(true);
298 /// let atomic_false = AtomicBool::new(false);
301 #[stable(feature = "rust1", since = "1.0.0")]
302 #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
304 pub const fn new(v: bool) -> AtomicBool {
305 AtomicBool { v: UnsafeCell::new(v as u8) }
308 /// Returns a mutable reference to the underlying [`bool`].
310 /// This is safe because the mutable reference guarantees that no other threads are
311 /// concurrently accessing the atomic data.
316 /// use std::sync::atomic::{AtomicBool, Ordering};
318 /// let mut some_bool = AtomicBool::new(true);
319 /// assert_eq!(*some_bool.get_mut(), true);
320 /// *some_bool.get_mut() = false;
321 /// assert_eq!(some_bool.load(Ordering::SeqCst), false);
324 #[stable(feature = "atomic_access", since = "1.15.0")]
325 pub fn get_mut(&mut self) -> &mut bool {
326 // SAFETY: the mutable reference guarantees unique ownership.
327 unsafe { &mut *(self.v.get() as *mut bool) }
330 /// Get atomic access to a `&mut bool`.
335 /// #![feature(atomic_from_mut)]
336 /// use std::sync::atomic::{AtomicBool, Ordering};
338 /// let mut some_bool = true;
339 /// let a = AtomicBool::from_mut(&mut some_bool);
340 /// a.store(false, Ordering::Relaxed);
341 /// assert_eq!(some_bool, false);
344 #[cfg(target_has_atomic_equal_alignment = "8")]
345 #[unstable(feature = "atomic_from_mut", issue = "76314")]
346 pub fn from_mut(v: &mut bool) -> &mut Self {
347 // SAFETY: the mutable reference guarantees unique ownership, and
348 // alignment of both `bool` and `Self` is 1.
349 unsafe { &mut *(v as *mut bool as *mut Self) }
352 /// Get non-atomic access to a `&mut [AtomicBool]` slice.
354 /// This is safe because the mutable reference guarantees that no other threads are
355 /// concurrently accessing the atomic data.
360 /// #![feature(atomic_from_mut, inline_const)]
361 /// use std::sync::atomic::{AtomicBool, Ordering};
363 /// let mut some_bools = [const { AtomicBool::new(false) }; 10];
365 /// let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools);
366 /// assert_eq!(view, [false; 10]);
367 /// view[..5].copy_from_slice(&[true; 5]);
369 /// std::thread::scope(|s| {
370 /// for t in &some_bools[..5] {
371 /// s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true));
374 /// for f in &some_bools[5..] {
375 /// s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false));
380 #[unstable(feature = "atomic_from_mut", issue = "76314")]
381 pub fn get_mut_slice(this: &mut [Self]) -> &mut [bool] {
382 // SAFETY: the mutable reference guarantees unique ownership.
383 unsafe { &mut *(this as *mut [Self] as *mut [bool]) }
386 /// Get atomic access to a `&mut [bool]` slice.
391 /// #![feature(atomic_from_mut)]
392 /// use std::sync::atomic::{AtomicBool, Ordering};
394 /// let mut some_bools = [false; 10];
395 /// let a = &*AtomicBool::from_mut_slice(&mut some_bools);
396 /// std::thread::scope(|s| {
397 /// for i in 0..a.len() {
398 /// s.spawn(move || a[i].store(true, Ordering::Relaxed));
401 /// assert_eq!(some_bools, [true; 10]);
404 #[cfg(target_has_atomic_equal_alignment = "8")]
405 #[unstable(feature = "atomic_from_mut", issue = "76314")]
406 pub fn from_mut_slice(v: &mut [bool]) -> &mut [Self] {
407 // SAFETY: the mutable reference guarantees unique ownership, and
408 // alignment of both `bool` and `Self` is 1.
409 unsafe { &mut *(v as *mut [bool] as *mut [Self]) }
412 /// Consumes the atomic and returns the contained value.
414 /// This is safe because passing `self` by value guarantees that no other threads are
415 /// concurrently accessing the atomic data.
420 /// use std::sync::atomic::AtomicBool;
422 /// let some_bool = AtomicBool::new(true);
423 /// assert_eq!(some_bool.into_inner(), true);
426 #[stable(feature = "atomic_access", since = "1.15.0")]
427 #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
428 pub const fn into_inner(self) -> bool {
429 self.v.into_inner() != 0
432 /// Loads a value from the bool.
434 /// `load` takes an [`Ordering`] argument which describes the memory ordering
435 /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
439 /// Panics if `order` is [`Release`] or [`AcqRel`].
444 /// use std::sync::atomic::{AtomicBool, Ordering};
446 /// let some_bool = AtomicBool::new(true);
448 /// assert_eq!(some_bool.load(Ordering::Relaxed), true);
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn load(&self, order: Ordering) -> bool {
453 // SAFETY: any data races are prevented by atomic intrinsics and the raw
454 // pointer passed in is valid because we got it from a reference.
455 unsafe { atomic_load(self.v.get(), order) != 0 }
458 /// Stores a value into the bool.
460 /// `store` takes an [`Ordering`] argument which describes the memory ordering
461 /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
465 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
470 /// use std::sync::atomic::{AtomicBool, Ordering};
472 /// let some_bool = AtomicBool::new(true);
474 /// some_bool.store(false, Ordering::Relaxed);
475 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn store(&self, val: bool, order: Ordering) {
480 // SAFETY: any data races are prevented by atomic intrinsics and the raw
481 // pointer passed in is valid because we got it from a reference.
483 atomic_store(self.v.get(), val as u8, order);
487 /// Stores a value into the bool, returning the previous value.
489 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
490 /// of this operation. All ordering modes are possible. Note that using
491 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
492 /// using [`Release`] makes the load part [`Relaxed`].
494 /// **Note:** This method is only available on platforms that support atomic
495 /// operations on `u8`.
500 /// use std::sync::atomic::{AtomicBool, Ordering};
502 /// let some_bool = AtomicBool::new(true);
504 /// assert_eq!(some_bool.swap(false, Ordering::Relaxed), true);
505 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
508 #[stable(feature = "rust1", since = "1.0.0")]
509 #[cfg(target_has_atomic = "8")]
510 pub fn swap(&self, val: bool, order: Ordering) -> bool {
511 // SAFETY: data races are prevented by atomic intrinsics.
512 unsafe { atomic_swap(self.v.get(), val as u8, order) != 0 }
515 /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
517 /// The return value is always the previous value. If it is equal to `current`, then the value
520 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
521 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
522 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
523 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
524 /// happens, and using [`Release`] makes the load part [`Relaxed`].
526 /// **Note:** This method is only available on platforms that support atomic
527 /// operations on `u8`.
529 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
531 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
532 /// memory orderings:
534 /// Original | Success | Failure
535 /// -------- | ------- | -------
536 /// Relaxed | Relaxed | Relaxed
537 /// Acquire | Acquire | Acquire
538 /// Release | Release | Relaxed
539 /// AcqRel | AcqRel | Acquire
540 /// SeqCst | SeqCst | SeqCst
542 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
543 /// which allows the compiler to generate better assembly code when the compare and swap
544 /// is used in a loop.
549 /// use std::sync::atomic::{AtomicBool, Ordering};
551 /// let some_bool = AtomicBool::new(true);
553 /// assert_eq!(some_bool.compare_and_swap(true, false, Ordering::Relaxed), true);
554 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
556 /// assert_eq!(some_bool.compare_and_swap(true, true, Ordering::Relaxed), false);
557 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
560 #[stable(feature = "rust1", since = "1.0.0")]
563 note = "Use `compare_exchange` or `compare_exchange_weak` instead"
565 #[cfg(target_has_atomic = "8")]
566 pub fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> bool {
567 match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
573 /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
575 /// The return value is a result indicating whether the new value was written and containing
576 /// the previous value. On success this value is guaranteed to be equal to `current`.
578 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
579 /// ordering of this operation. `success` describes the required ordering for the
580 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
581 /// `failure` describes the required ordering for the load operation that takes place when
582 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
583 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
584 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
585 /// and must be equivalent to or weaker than the success ordering.
587 /// **Note:** This method is only available on platforms that support atomic
588 /// operations on `u8`.
593 /// use std::sync::atomic::{AtomicBool, Ordering};
595 /// let some_bool = AtomicBool::new(true);
597 /// assert_eq!(some_bool.compare_exchange(true,
599 /// Ordering::Acquire,
600 /// Ordering::Relaxed),
602 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
604 /// assert_eq!(some_bool.compare_exchange(true, true,
605 /// Ordering::SeqCst,
606 /// Ordering::Acquire),
608 /// assert_eq!(some_bool.load(Ordering::Relaxed), false);
611 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
612 #[doc(alias = "compare_and_swap")]
613 #[cfg(target_has_atomic = "8")]
614 pub fn compare_exchange(
620 ) -> Result<bool, bool> {
621 // SAFETY: data races are prevented by atomic intrinsics.
623 atomic_compare_exchange(self.v.get(), current as u8, new as u8, success, failure)
626 Err(x) => Err(x != 0),
630 /// Stores a value into the [`bool`] if the current value is the same as the `current` value.
632 /// Unlike [`AtomicBool::compare_exchange`], this function is allowed to spuriously fail even when the
633 /// comparison succeeds, which can result in more efficient code on some platforms. The
634 /// return value is a result indicating whether the new value was written and containing the
637 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
638 /// ordering of this operation. `success` describes the required ordering for the
639 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
640 /// `failure` describes the required ordering for the load operation that takes place when
641 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
642 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
643 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
644 /// and must be equivalent to or weaker than the success ordering.
646 /// **Note:** This method is only available on platforms that support atomic
647 /// operations on `u8`.
652 /// use std::sync::atomic::{AtomicBool, Ordering};
654 /// let val = AtomicBool::new(false);
657 /// let mut old = val.load(Ordering::Relaxed);
659 /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
661 /// Err(x) => old = x,
666 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
667 #[doc(alias = "compare_and_swap")]
668 #[cfg(target_has_atomic = "8")]
669 pub fn compare_exchange_weak(
675 ) -> Result<bool, bool> {
676 // SAFETY: data races are prevented by atomic intrinsics.
678 atomic_compare_exchange_weak(self.v.get(), current as u8, new as u8, success, failure)
681 Err(x) => Err(x != 0),
685 /// Logical "and" with a boolean value.
687 /// Performs a logical "and" operation on the current value and the argument `val`, and sets
688 /// the new value to the result.
690 /// Returns the previous value.
692 /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
693 /// of this operation. All ordering modes are possible. Note that using
694 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
695 /// using [`Release`] makes the load part [`Relaxed`].
697 /// **Note:** This method is only available on platforms that support atomic
698 /// operations on `u8`.
703 /// use std::sync::atomic::{AtomicBool, Ordering};
705 /// let foo = AtomicBool::new(true);
706 /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), true);
707 /// assert_eq!(foo.load(Ordering::SeqCst), false);
709 /// let foo = AtomicBool::new(true);
710 /// assert_eq!(foo.fetch_and(true, Ordering::SeqCst), true);
711 /// assert_eq!(foo.load(Ordering::SeqCst), true);
713 /// let foo = AtomicBool::new(false);
714 /// assert_eq!(foo.fetch_and(false, Ordering::SeqCst), false);
715 /// assert_eq!(foo.load(Ordering::SeqCst), false);
718 #[stable(feature = "rust1", since = "1.0.0")]
719 #[cfg(target_has_atomic = "8")]
720 pub fn fetch_and(&self, val: bool, order: Ordering) -> bool {
721 // SAFETY: data races are prevented by atomic intrinsics.
722 unsafe { atomic_and(self.v.get(), val as u8, order) != 0 }
725 /// Logical "nand" with a boolean value.
727 /// Performs a logical "nand" operation on the current value and the argument `val`, and sets
728 /// the new value to the result.
730 /// Returns the previous value.
732 /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
733 /// of this operation. All ordering modes are possible. Note that using
734 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
735 /// using [`Release`] makes the load part [`Relaxed`].
737 /// **Note:** This method is only available on platforms that support atomic
738 /// operations on `u8`.
743 /// use std::sync::atomic::{AtomicBool, Ordering};
745 /// let foo = AtomicBool::new(true);
746 /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), true);
747 /// assert_eq!(foo.load(Ordering::SeqCst), true);
749 /// let foo = AtomicBool::new(true);
750 /// assert_eq!(foo.fetch_nand(true, Ordering::SeqCst), true);
751 /// assert_eq!(foo.load(Ordering::SeqCst) as usize, 0);
752 /// assert_eq!(foo.load(Ordering::SeqCst), false);
754 /// let foo = AtomicBool::new(false);
755 /// assert_eq!(foo.fetch_nand(false, Ordering::SeqCst), false);
756 /// assert_eq!(foo.load(Ordering::SeqCst), true);
759 #[stable(feature = "rust1", since = "1.0.0")]
760 #[cfg(target_has_atomic = "8")]
761 pub fn fetch_nand(&self, val: bool, order: Ordering) -> bool {
762 // We can't use atomic_nand here because it can result in a bool with
763 // an invalid value. This happens because the atomic operation is done
764 // with an 8-bit integer internally, which would set the upper 7 bits.
765 // So we just use fetch_xor or swap instead.
768 // We must invert the bool.
769 self.fetch_xor(true, order)
771 // !(x & false) == true
772 // We must set the bool to true.
773 self.swap(true, order)
777 /// Logical "or" with a boolean value.
779 /// Performs a logical "or" operation on the current value and the argument `val`, and sets the
780 /// new value to the result.
782 /// Returns the previous value.
784 /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
785 /// of this operation. All ordering modes are possible. Note that using
786 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
787 /// using [`Release`] makes the load part [`Relaxed`].
789 /// **Note:** This method is only available on platforms that support atomic
790 /// operations on `u8`.
795 /// use std::sync::atomic::{AtomicBool, Ordering};
797 /// let foo = AtomicBool::new(true);
798 /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), true);
799 /// assert_eq!(foo.load(Ordering::SeqCst), true);
801 /// let foo = AtomicBool::new(true);
802 /// assert_eq!(foo.fetch_or(true, Ordering::SeqCst), true);
803 /// assert_eq!(foo.load(Ordering::SeqCst), true);
805 /// let foo = AtomicBool::new(false);
806 /// assert_eq!(foo.fetch_or(false, Ordering::SeqCst), false);
807 /// assert_eq!(foo.load(Ordering::SeqCst), false);
810 #[stable(feature = "rust1", since = "1.0.0")]
811 #[cfg(target_has_atomic = "8")]
812 pub fn fetch_or(&self, val: bool, order: Ordering) -> bool {
813 // SAFETY: data races are prevented by atomic intrinsics.
814 unsafe { atomic_or(self.v.get(), val as u8, order) != 0 }
817 /// Logical "xor" with a boolean value.
819 /// Performs a logical "xor" operation on the current value and the argument `val`, and sets
820 /// the new value to the result.
822 /// Returns the previous value.
824 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
825 /// of this operation. All ordering modes are possible. Note that using
826 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
827 /// using [`Release`] makes the load part [`Relaxed`].
829 /// **Note:** This method is only available on platforms that support atomic
830 /// operations on `u8`.
835 /// use std::sync::atomic::{AtomicBool, Ordering};
837 /// let foo = AtomicBool::new(true);
838 /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), true);
839 /// assert_eq!(foo.load(Ordering::SeqCst), true);
841 /// let foo = AtomicBool::new(true);
842 /// assert_eq!(foo.fetch_xor(true, Ordering::SeqCst), true);
843 /// assert_eq!(foo.load(Ordering::SeqCst), false);
845 /// let foo = AtomicBool::new(false);
846 /// assert_eq!(foo.fetch_xor(false, Ordering::SeqCst), false);
847 /// assert_eq!(foo.load(Ordering::SeqCst), false);
850 #[stable(feature = "rust1", since = "1.0.0")]
851 #[cfg(target_has_atomic = "8")]
852 pub fn fetch_xor(&self, val: bool, order: Ordering) -> bool {
853 // SAFETY: data races are prevented by atomic intrinsics.
854 unsafe { atomic_xor(self.v.get(), val as u8, order) != 0 }
857 /// Logical "not" with a boolean value.
859 /// Performs a logical "not" operation on the current value, and sets
860 /// the new value to the result.
862 /// Returns the previous value.
864 /// `fetch_not` takes an [`Ordering`] argument which describes the memory ordering
865 /// of this operation. All ordering modes are possible. Note that using
866 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
867 /// using [`Release`] makes the load part [`Relaxed`].
869 /// **Note:** This method is only available on platforms that support atomic
870 /// operations on `u8`.
875 /// #![feature(atomic_bool_fetch_not)]
876 /// use std::sync::atomic::{AtomicBool, Ordering};
878 /// let foo = AtomicBool::new(true);
879 /// assert_eq!(foo.fetch_not(Ordering::SeqCst), true);
880 /// assert_eq!(foo.load(Ordering::SeqCst), false);
882 /// let foo = AtomicBool::new(false);
883 /// assert_eq!(foo.fetch_not(Ordering::SeqCst), false);
884 /// assert_eq!(foo.load(Ordering::SeqCst), true);
887 #[unstable(feature = "atomic_bool_fetch_not", issue = "98485")]
888 #[cfg(target_has_atomic = "8")]
889 pub fn fetch_not(&self, order: Ordering) -> bool {
890 self.fetch_xor(true, order)
893 /// Returns a mutable pointer to the underlying [`bool`].
895 /// Doing non-atomic reads and writes on the resulting integer can be a data race.
896 /// This method is mostly useful for FFI, where the function signature may use
897 /// `*mut bool` instead of `&AtomicBool`.
899 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
900 /// atomic types work with interior mutability. All modifications of an atomic change the value
901 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
902 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same
903 /// restriction: operations on it must be atomic.
907 /// ```ignore (extern-declaration)
909 /// use std::sync::atomic::AtomicBool;
911 /// fn my_atomic_op(arg: *mut bool);
914 /// let mut atomic = AtomicBool::new(true);
916 /// my_atomic_op(atomic.as_mut_ptr());
921 #[unstable(feature = "atomic_mut_ptr", reason = "recently added", issue = "66893")]
922 pub fn as_mut_ptr(&self) -> *mut bool {
923 self.v.get() as *mut bool
926 /// Fetches the value, and applies a function to it that returns an optional
927 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
928 /// returned `Some(_)`, else `Err(previous_value)`.
930 /// Note: This may call the function multiple times if the value has been
931 /// changed from other threads in the meantime, as long as the function
932 /// returns `Some(_)`, but the function will have been applied only once to
933 /// the stored value.
935 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
936 /// ordering of this operation. The first describes the required ordering for
937 /// when the operation finally succeeds while the second describes the
938 /// required ordering for loads. These correspond to the success and failure
939 /// orderings of [`AtomicBool::compare_exchange`] respectively.
941 /// Using [`Acquire`] as success ordering makes the store part of this
942 /// operation [`Relaxed`], and using [`Release`] makes the final successful
943 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
944 /// [`Acquire`] or [`Relaxed`] and must be equivalent to or weaker than the
945 /// success ordering.
947 /// **Note:** This method is only available on platforms that support atomic
948 /// operations on `u8`.
953 /// use std::sync::atomic::{AtomicBool, Ordering};
955 /// let x = AtomicBool::new(false);
956 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(false));
957 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(false));
958 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(!x)), Ok(true));
959 /// assert_eq!(x.load(Ordering::SeqCst), false);
962 #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
963 #[cfg(target_has_atomic = "8")]
964 pub fn fetch_update<F>(
967 fetch_order: Ordering,
969 ) -> Result<bool, bool>
971 F: FnMut(bool) -> Option<bool>,
973 let mut prev = self.load(fetch_order);
974 while let Some(next) = f(prev) {
975 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
976 x @ Ok(_) => return x,
977 Err(next_prev) => prev = next_prev,
984 #[cfg(target_has_atomic_load_store = "ptr")]
985 impl<T> AtomicPtr<T> {
986 /// Creates a new `AtomicPtr`.
991 /// use std::sync::atomic::AtomicPtr;
993 /// let ptr = &mut 5;
994 /// let atomic_ptr = AtomicPtr::new(ptr);
997 #[stable(feature = "rust1", since = "1.0.0")]
998 #[rustc_const_stable(feature = "const_atomic_new", since = "1.24.0")]
999 pub const fn new(p: *mut T) -> AtomicPtr<T> {
1000 AtomicPtr { p: UnsafeCell::new(p) }
1003 /// Returns a mutable reference to the underlying pointer.
1005 /// This is safe because the mutable reference guarantees that no other threads are
1006 /// concurrently accessing the atomic data.
1011 /// use std::sync::atomic::{AtomicPtr, Ordering};
1013 /// let mut data = 10;
1014 /// let mut atomic_ptr = AtomicPtr::new(&mut data);
1015 /// let mut other_data = 5;
1016 /// *atomic_ptr.get_mut() = &mut other_data;
1017 /// assert_eq!(unsafe { *atomic_ptr.load(Ordering::SeqCst) }, 5);
1020 #[stable(feature = "atomic_access", since = "1.15.0")]
1021 pub fn get_mut(&mut self) -> &mut *mut T {
1025 /// Get atomic access to a pointer.
1030 /// #![feature(atomic_from_mut)]
1031 /// use std::sync::atomic::{AtomicPtr, Ordering};
1033 /// let mut data = 123;
1034 /// let mut some_ptr = &mut data as *mut i32;
1035 /// let a = AtomicPtr::from_mut(&mut some_ptr);
1036 /// let mut other_data = 456;
1037 /// a.store(&mut other_data, Ordering::Relaxed);
1038 /// assert_eq!(unsafe { *some_ptr }, 456);
1041 #[cfg(target_has_atomic_equal_alignment = "ptr")]
1042 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1043 pub fn from_mut(v: &mut *mut T) -> &mut Self {
1044 use crate::mem::align_of;
1045 let [] = [(); align_of::<AtomicPtr<()>>() - align_of::<*mut ()>()];
1047 // - the mutable reference guarantees unique ownership.
1048 // - the alignment of `*mut T` and `Self` is the same on all platforms
1049 // supported by rust, as verified above.
1050 unsafe { &mut *(v as *mut *mut T as *mut Self) }
1053 /// Get non-atomic access to a `&mut [AtomicPtr]` slice.
1055 /// This is safe because the mutable reference guarantees that no other threads are
1056 /// concurrently accessing the atomic data.
1061 /// #![feature(atomic_from_mut, inline_const)]
1062 /// use std::ptr::null_mut;
1063 /// use std::sync::atomic::{AtomicPtr, Ordering};
1065 /// let mut some_ptrs = [const { AtomicPtr::new(null_mut::<String>()) }; 10];
1067 /// let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs);
1068 /// assert_eq!(view, [null_mut::<String>(); 10]);
1072 /// .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}"))));
1074 /// std::thread::scope(|s| {
1075 /// for ptr in &some_ptrs {
1076 /// s.spawn(move || {
1077 /// let ptr = ptr.load(Ordering::Relaxed);
1078 /// assert!(!ptr.is_null());
1080 /// let name = unsafe { Box::from_raw(ptr) };
1081 /// println!("Hello, {name}!");
1087 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1088 pub fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T] {
1089 // SAFETY: the mutable reference guarantees unique ownership.
1090 unsafe { &mut *(this as *mut [Self] as *mut [*mut T]) }
1093 /// Get atomic access to a slice of pointers.
1098 /// #![feature(atomic_from_mut)]
1099 /// use std::ptr::null_mut;
1100 /// use std::sync::atomic::{AtomicPtr, Ordering};
1102 /// let mut some_ptrs = [null_mut::<String>(); 10];
1103 /// let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs);
1104 /// std::thread::scope(|s| {
1105 /// for i in 0..a.len() {
1106 /// s.spawn(move || {
1107 /// let name = Box::new(format!("thread{i}"));
1108 /// a[i].store(Box::into_raw(name), Ordering::Relaxed);
1112 /// for p in some_ptrs {
1113 /// assert!(!p.is_null());
1114 /// let name = unsafe { Box::from_raw(p) };
1115 /// println!("Hello, {name}!");
1119 #[cfg(target_has_atomic_equal_alignment = "ptr")]
1120 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1121 pub fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self] {
1123 // - the mutable reference guarantees unique ownership.
1124 // - the alignment of `*mut T` and `Self` is the same on all platforms
1125 // supported by rust, as verified above.
1126 unsafe { &mut *(v as *mut [*mut T] as *mut [Self]) }
1129 /// Consumes the atomic and returns the contained value.
1131 /// This is safe because passing `self` by value guarantees that no other threads are
1132 /// concurrently accessing the atomic data.
1137 /// use std::sync::atomic::AtomicPtr;
1139 /// let mut data = 5;
1140 /// let atomic_ptr = AtomicPtr::new(&mut data);
1141 /// assert_eq!(unsafe { *atomic_ptr.into_inner() }, 5);
1144 #[stable(feature = "atomic_access", since = "1.15.0")]
1145 #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
1146 pub const fn into_inner(self) -> *mut T {
1150 /// Loads a value from the pointer.
1152 /// `load` takes an [`Ordering`] argument which describes the memory ordering
1153 /// of this operation. Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
1157 /// Panics if `order` is [`Release`] or [`AcqRel`].
1162 /// use std::sync::atomic::{AtomicPtr, Ordering};
1164 /// let ptr = &mut 5;
1165 /// let some_ptr = AtomicPtr::new(ptr);
1167 /// let value = some_ptr.load(Ordering::Relaxed);
1170 #[stable(feature = "rust1", since = "1.0.0")]
1171 pub fn load(&self, order: Ordering) -> *mut T {
1172 // SAFETY: data races are prevented by atomic intrinsics.
1173 unsafe { atomic_load(self.p.get(), order) }
1176 /// Stores a value into the pointer.
1178 /// `store` takes an [`Ordering`] argument which describes the memory ordering
1179 /// of this operation. Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
1183 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
1188 /// use std::sync::atomic::{AtomicPtr, Ordering};
1190 /// let ptr = &mut 5;
1191 /// let some_ptr = AtomicPtr::new(ptr);
1193 /// let other_ptr = &mut 10;
1195 /// some_ptr.store(other_ptr, Ordering::Relaxed);
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub fn store(&self, ptr: *mut T, order: Ordering) {
1200 // SAFETY: data races are prevented by atomic intrinsics.
1202 atomic_store(self.p.get(), ptr, order);
1206 /// Stores a value into the pointer, returning the previous value.
1208 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
1209 /// of this operation. All ordering modes are possible. Note that using
1210 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
1211 /// using [`Release`] makes the load part [`Relaxed`].
1213 /// **Note:** This method is only available on platforms that support atomic
1214 /// operations on pointers.
1219 /// use std::sync::atomic::{AtomicPtr, Ordering};
1221 /// let ptr = &mut 5;
1222 /// let some_ptr = AtomicPtr::new(ptr);
1224 /// let other_ptr = &mut 10;
1226 /// let value = some_ptr.swap(other_ptr, Ordering::Relaxed);
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 #[cfg(target_has_atomic = "ptr")]
1231 pub fn swap(&self, ptr: *mut T, order: Ordering) -> *mut T {
1232 // SAFETY: data races are prevented by atomic intrinsics.
1233 unsafe { atomic_swap(self.p.get(), ptr, order) }
1236 /// Stores a value into the pointer if the current value is the same as the `current` value.
1238 /// The return value is always the previous value. If it is equal to `current`, then the value
1241 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
1242 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
1243 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
1244 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
1245 /// happens, and using [`Release`] makes the load part [`Relaxed`].
1247 /// **Note:** This method is only available on platforms that support atomic
1248 /// operations on pointers.
1250 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
1252 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
1253 /// memory orderings:
1255 /// Original | Success | Failure
1256 /// -------- | ------- | -------
1257 /// Relaxed | Relaxed | Relaxed
1258 /// Acquire | Acquire | Acquire
1259 /// Release | Release | Relaxed
1260 /// AcqRel | AcqRel | Acquire
1261 /// SeqCst | SeqCst | SeqCst
1263 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
1264 /// which allows the compiler to generate better assembly code when the compare and swap
1265 /// is used in a loop.
1270 /// use std::sync::atomic::{AtomicPtr, Ordering};
1272 /// let ptr = &mut 5;
1273 /// let some_ptr = AtomicPtr::new(ptr);
1275 /// let other_ptr = &mut 10;
1277 /// let value = some_ptr.compare_and_swap(ptr, other_ptr, Ordering::Relaxed);
1280 #[stable(feature = "rust1", since = "1.0.0")]
1283 note = "Use `compare_exchange` or `compare_exchange_weak` instead"
1285 #[cfg(target_has_atomic = "ptr")]
1286 pub fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut T {
1287 match self.compare_exchange(current, new, order, strongest_failure_ordering(order)) {
1293 /// Stores a value into the pointer if the current value is the same as the `current` value.
1295 /// The return value is a result indicating whether the new value was written and containing
1296 /// the previous value. On success this value is guaranteed to be equal to `current`.
1298 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
1299 /// ordering of this operation. `success` describes the required ordering for the
1300 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1301 /// `failure` describes the required ordering for the load operation that takes place when
1302 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1303 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1304 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
1305 /// and must be equivalent to or weaker than the success ordering.
1307 /// **Note:** This method is only available on platforms that support atomic
1308 /// operations on pointers.
1313 /// use std::sync::atomic::{AtomicPtr, Ordering};
1315 /// let ptr = &mut 5;
1316 /// let some_ptr = AtomicPtr::new(ptr);
1318 /// let other_ptr = &mut 10;
1320 /// let value = some_ptr.compare_exchange(ptr, other_ptr,
1321 /// Ordering::SeqCst, Ordering::Relaxed);
1324 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1325 #[cfg(target_has_atomic = "ptr")]
1326 pub fn compare_exchange(
1332 ) -> Result<*mut T, *mut T> {
1333 // SAFETY: data races are prevented by atomic intrinsics.
1334 unsafe { atomic_compare_exchange(self.p.get(), current, new, success, failure) }
1337 /// Stores a value into the pointer if the current value is the same as the `current` value.
1339 /// Unlike [`AtomicPtr::compare_exchange`], this function is allowed to spuriously fail even when the
1340 /// comparison succeeds, which can result in more efficient code on some platforms. The
1341 /// return value is a result indicating whether the new value was written and containing the
1344 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
1345 /// ordering of this operation. `success` describes the required ordering for the
1346 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
1347 /// `failure` describes the required ordering for the load operation that takes place when
1348 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
1349 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
1350 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
1351 /// and must be equivalent to or weaker than the success ordering.
1353 /// **Note:** This method is only available on platforms that support atomic
1354 /// operations on pointers.
1359 /// use std::sync::atomic::{AtomicPtr, Ordering};
1361 /// let some_ptr = AtomicPtr::new(&mut 5);
1363 /// let new = &mut 10;
1364 /// let mut old = some_ptr.load(Ordering::Relaxed);
1366 /// match some_ptr.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
1368 /// Err(x) => old = x,
1373 #[stable(feature = "extended_compare_and_swap", since = "1.10.0")]
1374 #[cfg(target_has_atomic = "ptr")]
1375 pub fn compare_exchange_weak(
1381 ) -> Result<*mut T, *mut T> {
1382 // SAFETY: This intrinsic is unsafe because it operates on a raw pointer
1383 // but we know for sure that the pointer is valid (we just got it from
1384 // an `UnsafeCell` that we have by reference) and the atomic operation
1385 // itself allows us to safely mutate the `UnsafeCell` contents.
1386 unsafe { atomic_compare_exchange_weak(self.p.get(), current, new, success, failure) }
1389 /// Fetches the value, and applies a function to it that returns an optional
1390 /// new value. Returns a `Result` of `Ok(previous_value)` if the function
1391 /// returned `Some(_)`, else `Err(previous_value)`.
1393 /// Note: This may call the function multiple times if the value has been
1394 /// changed from other threads in the meantime, as long as the function
1395 /// returns `Some(_)`, but the function will have been applied only once to
1396 /// the stored value.
1398 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory
1399 /// ordering of this operation. The first describes the required ordering for
1400 /// when the operation finally succeeds while the second describes the
1401 /// required ordering for loads. These correspond to the success and failure
1402 /// orderings of [`AtomicPtr::compare_exchange`] respectively.
1404 /// Using [`Acquire`] as success ordering makes the store part of this
1405 /// operation [`Relaxed`], and using [`Release`] makes the final successful
1406 /// load [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`],
1407 /// [`Acquire`] or [`Relaxed`] and must be equivalent to or weaker than the
1408 /// success ordering.
1410 /// **Note:** This method is only available on platforms that support atomic
1411 /// operations on pointers.
1416 /// use std::sync::atomic::{AtomicPtr, Ordering};
1418 /// let ptr: *mut _ = &mut 5;
1419 /// let some_ptr = AtomicPtr::new(ptr);
1421 /// let new: *mut _ = &mut 10;
1422 /// assert_eq!(some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(ptr));
1423 /// let result = some_ptr.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| {
1430 /// assert_eq!(result, Ok(ptr));
1431 /// assert_eq!(some_ptr.load(Ordering::SeqCst), new);
1434 #[stable(feature = "atomic_fetch_update", since = "1.53.0")]
1435 #[cfg(target_has_atomic = "ptr")]
1436 pub fn fetch_update<F>(
1438 set_order: Ordering,
1439 fetch_order: Ordering,
1441 ) -> Result<*mut T, *mut T>
1443 F: FnMut(*mut T) -> Option<*mut T>,
1445 let mut prev = self.load(fetch_order);
1446 while let Some(next) = f(prev) {
1447 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
1448 x @ Ok(_) => return x,
1449 Err(next_prev) => prev = next_prev,
1455 /// Offsets the pointer's address by adding `val` (in units of `T`),
1456 /// returning the previous pointer.
1458 /// This is equivalent to using [`wrapping_add`] to atomically perform the
1459 /// equivalent of `ptr = ptr.wrapping_add(val);`.
1461 /// This method operates in units of `T`, which means that it cannot be used
1462 /// to offset the pointer by an amount which is not a multiple of
1463 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
1464 /// work with a deliberately misaligned pointer. In such cases, you may use
1465 /// the [`fetch_byte_add`](Self::fetch_byte_add) method instead.
1467 /// `fetch_ptr_add` takes an [`Ordering`] argument which describes the
1468 /// memory ordering of this operation. All ordering modes are possible. Note
1469 /// that using [`Acquire`] makes the store part of this operation
1470 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
1472 /// **Note**: This method is only available on platforms that support atomic
1473 /// operations on [`AtomicPtr`].
1475 /// [`wrapping_add`]: pointer::wrapping_add
1480 /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1481 /// use core::sync::atomic::{AtomicPtr, Ordering};
1483 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
1484 /// assert_eq!(atom.fetch_ptr_add(1, Ordering::Relaxed).addr(), 0);
1485 /// // Note: units of `size_of::<i64>()`.
1486 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 8);
1489 #[cfg(target_has_atomic = "ptr")]
1490 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1491 pub fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut T {
1492 self.fetch_byte_add(val.wrapping_mul(core::mem::size_of::<T>()), order)
1495 /// Offsets the pointer's address by subtracting `val` (in units of `T`),
1496 /// returning the previous pointer.
1498 /// This is equivalent to using [`wrapping_sub`] to atomically perform the
1499 /// equivalent of `ptr = ptr.wrapping_sub(val);`.
1501 /// This method operates in units of `T`, which means that it cannot be used
1502 /// to offset the pointer by an amount which is not a multiple of
1503 /// `size_of::<T>()`. This can sometimes be inconvenient, as you may want to
1504 /// work with a deliberately misaligned pointer. In such cases, you may use
1505 /// the [`fetch_byte_sub`](Self::fetch_byte_sub) method instead.
1507 /// `fetch_ptr_sub` takes an [`Ordering`] argument which describes the memory
1508 /// ordering of this operation. All ordering modes are possible. Note that
1509 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
1510 /// and using [`Release`] makes the load part [`Relaxed`].
1512 /// **Note**: This method is only available on platforms that support atomic
1513 /// operations on [`AtomicPtr`].
1515 /// [`wrapping_sub`]: pointer::wrapping_sub
1520 /// #![feature(strict_provenance_atomic_ptr)]
1521 /// use core::sync::atomic::{AtomicPtr, Ordering};
1523 /// let array = [1i32, 2i32];
1524 /// let atom = AtomicPtr::new(array.as_ptr().wrapping_add(1) as *mut _);
1526 /// assert!(core::ptr::eq(
1527 /// atom.fetch_ptr_sub(1, Ordering::Relaxed),
1530 /// assert!(core::ptr::eq(atom.load(Ordering::Relaxed), &array[0]));
1533 #[cfg(target_has_atomic = "ptr")]
1534 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1535 pub fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut T {
1536 self.fetch_byte_sub(val.wrapping_mul(core::mem::size_of::<T>()), order)
1539 /// Offsets the pointer's address by adding `val` *bytes*, returning the
1540 /// previous pointer.
1542 /// This is equivalent to using [`wrapping_add`] and [`cast`] to atomically
1543 /// perform `ptr = ptr.cast::<u8>().wrapping_add(val).cast::<T>()`.
1545 /// `fetch_byte_add` takes an [`Ordering`] argument which describes the
1546 /// memory ordering of this operation. All ordering modes are possible. Note
1547 /// that using [`Acquire`] makes the store part of this operation
1548 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
1550 /// **Note**: This method is only available on platforms that support atomic
1551 /// operations on [`AtomicPtr`].
1553 /// [`wrapping_add`]: pointer::wrapping_add
1554 /// [`cast`]: pointer::cast
1559 /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1560 /// use core::sync::atomic::{AtomicPtr, Ordering};
1562 /// let atom = AtomicPtr::<i64>::new(core::ptr::null_mut());
1563 /// assert_eq!(atom.fetch_byte_add(1, Ordering::Relaxed).addr(), 0);
1564 /// // Note: in units of bytes, not `size_of::<i64>()`.
1565 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 1);
1568 #[cfg(target_has_atomic = "ptr")]
1569 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1570 pub fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut T {
1571 #[cfg(not(bootstrap))]
1572 // SAFETY: data races are prevented by atomic intrinsics.
1574 atomic_add(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1577 // SAFETY: data races are prevented by atomic intrinsics.
1579 atomic_add(self.p.get().cast::<usize>(), val, order) as *mut T
1583 /// Offsets the pointer's address by subtracting `val` *bytes*, returning the
1584 /// previous pointer.
1586 /// This is equivalent to using [`wrapping_sub`] and [`cast`] to atomically
1587 /// perform `ptr = ptr.cast::<u8>().wrapping_sub(val).cast::<T>()`.
1589 /// `fetch_byte_sub` takes an [`Ordering`] argument which describes the
1590 /// memory ordering of this operation. All ordering modes are possible. Note
1591 /// that using [`Acquire`] makes the store part of this operation
1592 /// [`Relaxed`], and using [`Release`] makes the load part [`Relaxed`].
1594 /// **Note**: This method is only available on platforms that support atomic
1595 /// operations on [`AtomicPtr`].
1597 /// [`wrapping_sub`]: pointer::wrapping_sub
1598 /// [`cast`]: pointer::cast
1603 /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1604 /// use core::sync::atomic::{AtomicPtr, Ordering};
1606 /// let atom = AtomicPtr::<i64>::new(core::ptr::invalid_mut(1));
1607 /// assert_eq!(atom.fetch_byte_sub(1, Ordering::Relaxed).addr(), 1);
1608 /// assert_eq!(atom.load(Ordering::Relaxed).addr(), 0);
1611 #[cfg(target_has_atomic = "ptr")]
1612 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1613 pub fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut T {
1614 #[cfg(not(bootstrap))]
1615 // SAFETY: data races are prevented by atomic intrinsics.
1617 atomic_sub(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1620 // SAFETY: data races are prevented by atomic intrinsics.
1622 atomic_sub(self.p.get().cast::<usize>(), val, order) as *mut T
1626 /// Performs a bitwise "or" operation on the address of the current pointer,
1627 /// and the argument `val`, and stores a pointer with provenance of the
1628 /// current pointer and the resulting address.
1630 /// This is equivalent equivalent to using [`map_addr`] to atomically
1631 /// perform `ptr = ptr.map_addr(|a| a | val)`. This can be used in tagged
1632 /// pointer schemes to atomically set tag bits.
1634 /// **Caveat**: This operation returns the previous value. To compute the
1635 /// stored value without losing provenance, you may use [`map_addr`]. For
1636 /// example: `a.fetch_or(val).map_addr(|a| a | val)`.
1638 /// `fetch_or` takes an [`Ordering`] argument which describes the memory
1639 /// ordering of this operation. All ordering modes are possible. Note that
1640 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
1641 /// and using [`Release`] makes the load part [`Relaxed`].
1643 /// **Note**: This method is only available on platforms that support atomic
1644 /// operations on [`AtomicPtr`].
1646 /// This API and its claimed semantics are part of the Strict Provenance
1647 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
1650 /// [`map_addr`]: pointer::map_addr
1655 /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1656 /// use core::sync::atomic::{AtomicPtr, Ordering};
1658 /// let pointer = &mut 3i64 as *mut i64;
1660 /// let atom = AtomicPtr::<i64>::new(pointer);
1661 /// // Tag the bottom bit of the pointer.
1662 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 0);
1663 /// // Extract and untag.
1664 /// let tagged = atom.load(Ordering::Relaxed);
1665 /// assert_eq!(tagged.addr() & 1, 1);
1666 /// assert_eq!(tagged.map_addr(|p| p & !1), pointer);
1669 #[cfg(target_has_atomic = "ptr")]
1670 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1671 pub fn fetch_or(&self, val: usize, order: Ordering) -> *mut T {
1672 #[cfg(not(bootstrap))]
1673 // SAFETY: data races are prevented by atomic intrinsics.
1675 atomic_or(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1678 // SAFETY: data races are prevented by atomic intrinsics.
1680 atomic_or(self.p.get().cast::<usize>(), val, order) as *mut T
1684 /// Performs a bitwise "and" operation on the address of the current
1685 /// pointer, and the argument `val`, and stores a pointer with provenance of
1686 /// the current pointer and the resulting address.
1688 /// This is equivalent equivalent to using [`map_addr`] to atomically
1689 /// perform `ptr = ptr.map_addr(|a| a & val)`. This can be used in tagged
1690 /// pointer schemes to atomically unset tag bits.
1692 /// **Caveat**: This operation returns the previous value. To compute the
1693 /// stored value without losing provenance, you may use [`map_addr`]. For
1694 /// example: `a.fetch_and(val).map_addr(|a| a & val)`.
1696 /// `fetch_and` takes an [`Ordering`] argument which describes the memory
1697 /// ordering of this operation. All ordering modes are possible. Note that
1698 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
1699 /// and using [`Release`] makes the load part [`Relaxed`].
1701 /// **Note**: This method is only available on platforms that support atomic
1702 /// operations on [`AtomicPtr`].
1704 /// This API and its claimed semantics are part of the Strict Provenance
1705 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
1708 /// [`map_addr`]: pointer::map_addr
1713 /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1714 /// use core::sync::atomic::{AtomicPtr, Ordering};
1716 /// let pointer = &mut 3i64 as *mut i64;
1717 /// // A tagged pointer
1718 /// let atom = AtomicPtr::<i64>::new(pointer.map_addr(|a| a | 1));
1719 /// assert_eq!(atom.fetch_or(1, Ordering::Relaxed).addr() & 1, 1);
1720 /// // Untag, and extract the previously tagged pointer.
1721 /// let untagged = atom.fetch_and(!1, Ordering::Relaxed)
1722 /// .map_addr(|a| a & !1);
1723 /// assert_eq!(untagged, pointer);
1726 #[cfg(target_has_atomic = "ptr")]
1727 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1728 pub fn fetch_and(&self, val: usize, order: Ordering) -> *mut T {
1729 #[cfg(not(bootstrap))]
1730 // SAFETY: data races are prevented by atomic intrinsics.
1732 atomic_and(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1735 // SAFETY: data races are prevented by atomic intrinsics.
1737 atomic_and(self.p.get().cast::<usize>(), val, order) as *mut T
1741 /// Performs a bitwise "xor" operation on the address of the current
1742 /// pointer, and the argument `val`, and stores a pointer with provenance of
1743 /// the current pointer and the resulting address.
1745 /// This is equivalent equivalent to using [`map_addr`] to atomically
1746 /// perform `ptr = ptr.map_addr(|a| a ^ val)`. This can be used in tagged
1747 /// pointer schemes to atomically toggle tag bits.
1749 /// **Caveat**: This operation returns the previous value. To compute the
1750 /// stored value without losing provenance, you may use [`map_addr`]. For
1751 /// example: `a.fetch_xor(val).map_addr(|a| a ^ val)`.
1753 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory
1754 /// ordering of this operation. All ordering modes are possible. Note that
1755 /// using [`Acquire`] makes the store part of this operation [`Relaxed`],
1756 /// and using [`Release`] makes the load part [`Relaxed`].
1758 /// **Note**: This method is only available on platforms that support atomic
1759 /// operations on [`AtomicPtr`].
1761 /// This API and its claimed semantics are part of the Strict Provenance
1762 /// experiment, see the [module documentation for `ptr`][crate::ptr] for
1765 /// [`map_addr`]: pointer::map_addr
1770 /// #![feature(strict_provenance_atomic_ptr, strict_provenance)]
1771 /// use core::sync::atomic::{AtomicPtr, Ordering};
1773 /// let pointer = &mut 3i64 as *mut i64;
1774 /// let atom = AtomicPtr::<i64>::new(pointer);
1776 /// // Toggle a tag bit on the pointer.
1777 /// atom.fetch_xor(1, Ordering::Relaxed);
1778 /// assert_eq!(atom.load(Ordering::Relaxed).addr() & 1, 1);
1781 #[cfg(target_has_atomic = "ptr")]
1782 #[unstable(feature = "strict_provenance_atomic_ptr", issue = "99108")]
1783 pub fn fetch_xor(&self, val: usize, order: Ordering) -> *mut T {
1784 #[cfg(not(bootstrap))]
1785 // SAFETY: data races are prevented by atomic intrinsics.
1787 atomic_xor(self.p.get(), core::ptr::invalid_mut(val), order).cast()
1790 // SAFETY: data races are prevented by atomic intrinsics.
1792 atomic_xor(self.p.get().cast::<usize>(), val, order) as *mut T
1797 #[cfg(target_has_atomic_load_store = "8")]
1798 #[stable(feature = "atomic_bool_from", since = "1.24.0")]
1799 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1800 impl const From<bool> for AtomicBool {
1801 /// Converts a `bool` into an `AtomicBool`.
1806 /// use std::sync::atomic::AtomicBool;
1807 /// let atomic_bool = AtomicBool::from(true);
1808 /// assert_eq!(format!("{atomic_bool:?}"), "true")
1811 fn from(b: bool) -> Self {
1816 #[cfg(target_has_atomic_load_store = "ptr")]
1817 #[stable(feature = "atomic_from", since = "1.23.0")]
1818 #[rustc_const_unstable(feature = "const_convert", issue = "88674")]
1819 impl<T> const From<*mut T> for AtomicPtr<T> {
1820 /// Converts a `*mut T` into an `AtomicPtr<T>`.
1822 fn from(p: *mut T) -> Self {
1827 #[allow(unused_macros)] // This macro ends up being unused on some architectures.
1828 macro_rules! if_not_8_bit {
1829 (u8, $($tt:tt)*) => { "" };
1830 (i8, $($tt:tt)*) => { "" };
1831 ($_:ident, $($tt:tt)*) => { $($tt)* };
1834 #[cfg(target_has_atomic_load_store = "8")]
1835 macro_rules! atomic_int {
1841 $stable_access:meta,
1845 $stable_init_const:meta,
1846 $diagnostic_item:meta,
1847 $s_int_type:literal,
1848 $extra_feature:expr,
1849 $min_fn:ident, $max_fn:ident,
1852 $int_type:ident $atomic_type:ident $atomic_init:ident) => {
1853 /// An integer type which can be safely shared between threads.
1855 /// This type has the same in-memory representation as the underlying
1856 /// integer type, [`
1857 #[doc = $s_int_type]
1858 /// `]. For more about the differences between atomic types and
1859 /// non-atomic types as well as information about the portability of
1860 /// this type, please see the [module-level documentation].
1862 /// **Note:** This type is only available on platforms that support
1863 /// atomic loads and stores of [`
1864 #[doc = $s_int_type]
1867 /// [module-level documentation]: crate::sync::atomic
1870 #[repr(C, align($align))]
1871 pub struct $atomic_type {
1872 v: UnsafeCell<$int_type>,
1875 /// An atomic integer initialized to `0`.
1876 #[$stable_init_const]
1879 note = "the `new` function is now preferred",
1880 suggestion = $atomic_new,
1882 pub const $atomic_init: $atomic_type = $atomic_type::new(0);
1885 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1886 impl const Default for $atomic_type {
1888 fn default() -> Self {
1889 Self::new(Default::default())
1894 #[rustc_const_unstable(feature = "const_num_from_num", issue = "87852")]
1895 impl const From<$int_type> for $atomic_type {
1896 #[doc = concat!("Converts an `", stringify!($int_type), "` into an `", stringify!($atomic_type), "`.")]
1898 fn from(v: $int_type) -> Self { Self::new(v) }
1902 impl fmt::Debug for $atomic_type {
1903 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1904 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
1908 // Send is implicitly implemented.
1910 unsafe impl Sync for $atomic_type {}
1913 /// Creates a new atomic integer.
1918 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
1920 #[doc = concat!("let atomic_forty_two = ", stringify!($atomic_type), "::new(42);")]
1926 pub const fn new(v: $int_type) -> Self {
1927 Self {v: UnsafeCell::new(v)}
1930 /// Returns a mutable reference to the underlying integer.
1932 /// This is safe because the mutable reference guarantees that no other threads are
1933 /// concurrently accessing the atomic data.
1938 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
1940 #[doc = concat!("let mut some_var = ", stringify!($atomic_type), "::new(10);")]
1941 /// assert_eq!(*some_var.get_mut(), 10);
1942 /// *some_var.get_mut() = 5;
1943 /// assert_eq!(some_var.load(Ordering::SeqCst), 5);
1947 pub fn get_mut(&mut self) -> &mut $int_type {
1951 #[doc = concat!("Get atomic access to a `&mut ", stringify!($int_type), "`.")]
1953 #[doc = if_not_8_bit! {
1956 "**Note:** This function is only available on targets where `",
1957 stringify!($int_type), "` has an alignment of ", $align, " bytes."
1964 /// #![feature(atomic_from_mut)]
1965 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
1967 /// let mut some_int = 123;
1968 #[doc = concat!("let a = ", stringify!($atomic_type), "::from_mut(&mut some_int);")]
1969 /// a.store(100, Ordering::Relaxed);
1970 /// assert_eq!(some_int, 100);
1975 #[unstable(feature = "atomic_from_mut", issue = "76314")]
1976 pub fn from_mut(v: &mut $int_type) -> &mut Self {
1977 use crate::mem::align_of;
1978 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
1980 // - the mutable reference guarantees unique ownership.
1981 // - the alignment of `$int_type` and `Self` is the
1982 // same, as promised by $cfg_align and verified above.
1983 unsafe { &mut *(v as *mut $int_type as *mut Self) }
1986 #[doc = concat!("Get non-atomic access to a `&mut [", stringify!($atomic_type), "]` slice")]
1988 /// This is safe because the mutable reference guarantees that no other threads are
1989 /// concurrently accessing the atomic data.
1994 /// #![feature(atomic_from_mut, inline_const)]
1995 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
1997 #[doc = concat!("let mut some_ints = [const { ", stringify!($atomic_type), "::new(0) }; 10];")]
1999 #[doc = concat!("let view: &mut [", stringify!($int_type), "] = ", stringify!($atomic_type), "::get_mut_slice(&mut some_ints);")]
2000 /// assert_eq!(view, [0; 10]);
2004 /// .for_each(|(idx, int)| *int = idx as _);
2006 /// std::thread::scope(|s| {
2010 /// .for_each(|(idx, int)| {
2011 /// s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _));
2016 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2017 pub fn get_mut_slice(this: &mut [Self]) -> &mut [$int_type] {
2018 // SAFETY: the mutable reference guarantees unique ownership.
2019 unsafe { &mut *(this as *mut [Self] as *mut [$int_type]) }
2022 #[doc = concat!("Get atomic access to a `&mut [", stringify!($int_type), "]` slice.")]
2027 /// #![feature(atomic_from_mut)]
2028 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2030 /// let mut some_ints = [0; 10];
2031 #[doc = concat!("let a = &*", stringify!($atomic_type), "::from_mut_slice(&mut some_ints);")]
2032 /// std::thread::scope(|s| {
2033 /// for i in 0..a.len() {
2034 /// s.spawn(move || a[i].store(i as _, Ordering::Relaxed));
2037 /// for (i, n) in some_ints.into_iter().enumerate() {
2038 /// assert_eq!(i, n as usize);
2043 #[unstable(feature = "atomic_from_mut", issue = "76314")]
2044 pub fn from_mut_slice(v: &mut [$int_type]) -> &mut [Self] {
2045 use crate::mem::align_of;
2046 let [] = [(); align_of::<Self>() - align_of::<$int_type>()];
2048 // - the mutable reference guarantees unique ownership.
2049 // - the alignment of `$int_type` and `Self` is the
2050 // same, as promised by $cfg_align and verified above.
2051 unsafe { &mut *(v as *mut [$int_type] as *mut [Self]) }
2054 /// Consumes the atomic and returns the contained value.
2056 /// This is safe because passing `self` by value guarantees that no other threads are
2057 /// concurrently accessing the atomic data.
2062 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2064 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2065 /// assert_eq!(some_var.into_inner(), 5);
2069 #[rustc_const_unstable(feature = "const_cell_into_inner", issue = "78729")]
2070 pub const fn into_inner(self) -> $int_type {
2074 /// Loads a value from the atomic integer.
2076 /// `load` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2077 /// Possible values are [`SeqCst`], [`Acquire`] and [`Relaxed`].
2081 /// Panics if `order` is [`Release`] or [`AcqRel`].
2086 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2088 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2090 /// assert_eq!(some_var.load(Ordering::Relaxed), 5);
2094 pub fn load(&self, order: Ordering) -> $int_type {
2095 // SAFETY: data races are prevented by atomic intrinsics.
2096 unsafe { atomic_load(self.v.get(), order) }
2099 /// Stores a value into the atomic integer.
2101 /// `store` takes an [`Ordering`] argument which describes the memory ordering of this operation.
2102 /// Possible values are [`SeqCst`], [`Release`] and [`Relaxed`].
2106 /// Panics if `order` is [`Acquire`] or [`AcqRel`].
2111 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2113 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2115 /// some_var.store(10, Ordering::Relaxed);
2116 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2120 pub fn store(&self, val: $int_type, order: Ordering) {
2121 // SAFETY: data races are prevented by atomic intrinsics.
2122 unsafe { atomic_store(self.v.get(), val, order); }
2125 /// Stores a value into the atomic integer, returning the previous value.
2127 /// `swap` takes an [`Ordering`] argument which describes the memory ordering
2128 /// of this operation. All ordering modes are possible. Note that using
2129 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2130 /// using [`Release`] makes the load part [`Relaxed`].
2132 /// **Note**: This method is only available on platforms that support atomic operations on
2133 #[doc = concat!("[`", $s_int_type, "`].")]
2138 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2140 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2142 /// assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);
2147 pub fn swap(&self, val: $int_type, order: Ordering) -> $int_type {
2148 // SAFETY: data races are prevented by atomic intrinsics.
2149 unsafe { atomic_swap(self.v.get(), val, order) }
2152 /// Stores a value into the atomic integer if the current value is the same as
2153 /// the `current` value.
2155 /// The return value is always the previous value. If it is equal to `current`, then the
2156 /// value was updated.
2158 /// `compare_and_swap` also takes an [`Ordering`] argument which describes the memory
2159 /// ordering of this operation. Notice that even when using [`AcqRel`], the operation
2160 /// might fail and hence just perform an `Acquire` load, but not have `Release` semantics.
2161 /// Using [`Acquire`] makes the store part of this operation [`Relaxed`] if it
2162 /// happens, and using [`Release`] makes the load part [`Relaxed`].
2164 /// **Note**: This method is only available on platforms that support atomic operations on
2165 #[doc = concat!("[`", $s_int_type, "`].")]
2167 /// # Migrating to `compare_exchange` and `compare_exchange_weak`
2169 /// `compare_and_swap` is equivalent to `compare_exchange` with the following mapping for
2170 /// memory orderings:
2172 /// Original | Success | Failure
2173 /// -------- | ------- | -------
2174 /// Relaxed | Relaxed | Relaxed
2175 /// Acquire | Acquire | Acquire
2176 /// Release | Release | Relaxed
2177 /// AcqRel | AcqRel | Acquire
2178 /// SeqCst | SeqCst | SeqCst
2180 /// `compare_exchange_weak` is allowed to fail spuriously even when the comparison succeeds,
2181 /// which allows the compiler to generate better assembly code when the compare and swap
2182 /// is used in a loop.
2187 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2189 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2191 /// assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5);
2192 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2194 /// assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10);
2195 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2201 note = "Use `compare_exchange` or `compare_exchange_weak` instead")
2204 pub fn compare_and_swap(&self,
2207 order: Ordering) -> $int_type {
2208 match self.compare_exchange(current,
2211 strongest_failure_ordering(order)) {
2217 /// Stores a value into the atomic integer if the current value is the same as
2218 /// the `current` value.
2220 /// The return value is a result indicating whether the new value was written and
2221 /// containing the previous value. On success this value is guaranteed to be equal to
2224 /// `compare_exchange` takes two [`Ordering`] arguments to describe the memory
2225 /// ordering of this operation. `success` describes the required ordering for the
2226 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
2227 /// `failure` describes the required ordering for the load operation that takes place when
2228 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
2229 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
2230 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
2231 /// and must be equivalent to or weaker than the success ordering.
2233 /// **Note**: This method is only available on platforms that support atomic operations on
2234 #[doc = concat!("[`", $s_int_type, "`].")]
2239 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2241 #[doc = concat!("let some_var = ", stringify!($atomic_type), "::new(5);")]
2243 /// assert_eq!(some_var.compare_exchange(5, 10,
2244 /// Ordering::Acquire,
2245 /// Ordering::Relaxed),
2247 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2249 /// assert_eq!(some_var.compare_exchange(6, 12,
2250 /// Ordering::SeqCst,
2251 /// Ordering::Acquire),
2253 /// assert_eq!(some_var.load(Ordering::Relaxed), 10);
2258 pub fn compare_exchange(&self,
2262 failure: Ordering) -> Result<$int_type, $int_type> {
2263 // SAFETY: data races are prevented by atomic intrinsics.
2264 unsafe { atomic_compare_exchange(self.v.get(), current, new, success, failure) }
2267 /// Stores a value into the atomic integer if the current value is the same as
2268 /// the `current` value.
2270 #[doc = concat!("Unlike [`", stringify!($atomic_type), "::compare_exchange`],")]
2271 /// this function is allowed to spuriously fail even
2272 /// when the comparison succeeds, which can result in more efficient code on some
2273 /// platforms. The return value is a result indicating whether the new value was
2274 /// written and containing the previous value.
2276 /// `compare_exchange_weak` takes two [`Ordering`] arguments to describe the memory
2277 /// ordering of this operation. `success` describes the required ordering for the
2278 /// read-modify-write operation that takes place if the comparison with `current` succeeds.
2279 /// `failure` describes the required ordering for the load operation that takes place when
2280 /// the comparison fails. Using [`Acquire`] as success ordering makes the store part
2281 /// of this operation [`Relaxed`], and using [`Release`] makes the successful load
2282 /// [`Relaxed`]. The failure ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
2283 /// and must be equivalent to or weaker than the success ordering.
2285 /// **Note**: This method is only available on platforms that support atomic operations on
2286 #[doc = concat!("[`", $s_int_type, "`].")]
2291 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2293 #[doc = concat!("let val = ", stringify!($atomic_type), "::new(4);")]
2295 /// let mut old = val.load(Ordering::Relaxed);
2297 /// let new = old * 2;
2298 /// match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) {
2300 /// Err(x) => old = x,
2307 pub fn compare_exchange_weak(&self,
2311 failure: Ordering) -> Result<$int_type, $int_type> {
2312 // SAFETY: data races are prevented by atomic intrinsics.
2314 atomic_compare_exchange_weak(self.v.get(), current, new, success, failure)
2318 /// Adds to the current value, returning the previous value.
2320 /// This operation wraps around on overflow.
2322 /// `fetch_add` takes an [`Ordering`] argument which describes the memory ordering
2323 /// of this operation. All ordering modes are possible. Note that using
2324 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2325 /// using [`Release`] makes the load part [`Relaxed`].
2327 /// **Note**: This method is only available on platforms that support atomic operations on
2328 #[doc = concat!("[`", $s_int_type, "`].")]
2333 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2335 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0);")]
2336 /// assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0);
2337 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
2342 pub fn fetch_add(&self, val: $int_type, order: Ordering) -> $int_type {
2343 // SAFETY: data races are prevented by atomic intrinsics.
2344 unsafe { atomic_add(self.v.get(), val, order) }
2347 /// Subtracts from the current value, returning the previous value.
2349 /// This operation wraps around on overflow.
2351 /// `fetch_sub` takes an [`Ordering`] argument which describes the memory ordering
2352 /// of this operation. All ordering modes are possible. Note that using
2353 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2354 /// using [`Release`] makes the load part [`Relaxed`].
2356 /// **Note**: This method is only available on platforms that support atomic operations on
2357 #[doc = concat!("[`", $s_int_type, "`].")]
2362 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2364 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(20);")]
2365 /// assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20);
2366 /// assert_eq!(foo.load(Ordering::SeqCst), 10);
2371 pub fn fetch_sub(&self, val: $int_type, order: Ordering) -> $int_type {
2372 // SAFETY: data races are prevented by atomic intrinsics.
2373 unsafe { atomic_sub(self.v.get(), val, order) }
2376 /// Bitwise "and" with the current value.
2378 /// Performs a bitwise "and" operation on the current value and the argument `val`, and
2379 /// sets the new value to the result.
2381 /// Returns the previous value.
2383 /// `fetch_and` takes an [`Ordering`] argument which describes the memory ordering
2384 /// of this operation. All ordering modes are possible. Note that using
2385 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2386 /// using [`Release`] makes the load part [`Relaxed`].
2388 /// **Note**: This method is only available on platforms that support atomic operations on
2389 #[doc = concat!("[`", $s_int_type, "`].")]
2394 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2396 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
2397 /// assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101);
2398 /// assert_eq!(foo.load(Ordering::SeqCst), 0b100001);
2403 pub fn fetch_and(&self, val: $int_type, order: Ordering) -> $int_type {
2404 // SAFETY: data races are prevented by atomic intrinsics.
2405 unsafe { atomic_and(self.v.get(), val, order) }
2408 /// Bitwise "nand" with the current value.
2410 /// Performs a bitwise "nand" operation on the current value and the argument `val`, and
2411 /// sets the new value to the result.
2413 /// Returns the previous value.
2415 /// `fetch_nand` takes an [`Ordering`] argument which describes the memory ordering
2416 /// of this operation. All ordering modes are possible. Note that using
2417 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2418 /// using [`Release`] makes the load part [`Relaxed`].
2420 /// **Note**: This method is only available on platforms that support atomic operations on
2421 #[doc = concat!("[`", $s_int_type, "`].")]
2426 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2428 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0x13);")]
2429 /// assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13);
2430 /// assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));
2435 pub fn fetch_nand(&self, val: $int_type, order: Ordering) -> $int_type {
2436 // SAFETY: data races are prevented by atomic intrinsics.
2437 unsafe { atomic_nand(self.v.get(), val, order) }
2440 /// Bitwise "or" with the current value.
2442 /// Performs a bitwise "or" operation on the current value and the argument `val`, and
2443 /// sets the new value to the result.
2445 /// Returns the previous value.
2447 /// `fetch_or` takes an [`Ordering`] argument which describes the memory ordering
2448 /// of this operation. All ordering modes are possible. Note that using
2449 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2450 /// using [`Release`] makes the load part [`Relaxed`].
2452 /// **Note**: This method is only available on platforms that support atomic operations on
2453 #[doc = concat!("[`", $s_int_type, "`].")]
2458 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2460 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
2461 /// assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101);
2462 /// assert_eq!(foo.load(Ordering::SeqCst), 0b111111);
2467 pub fn fetch_or(&self, val: $int_type, order: Ordering) -> $int_type {
2468 // SAFETY: data races are prevented by atomic intrinsics.
2469 unsafe { atomic_or(self.v.get(), val, order) }
2472 /// Bitwise "xor" with the current value.
2474 /// Performs a bitwise "xor" operation on the current value and the argument `val`, and
2475 /// sets the new value to the result.
2477 /// Returns the previous value.
2479 /// `fetch_xor` takes an [`Ordering`] argument which describes the memory ordering
2480 /// of this operation. All ordering modes are possible. Note that using
2481 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2482 /// using [`Release`] makes the load part [`Relaxed`].
2484 /// **Note**: This method is only available on platforms that support atomic operations on
2485 #[doc = concat!("[`", $s_int_type, "`].")]
2490 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2492 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(0b101101);")]
2493 /// assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101);
2494 /// assert_eq!(foo.load(Ordering::SeqCst), 0b011110);
2499 pub fn fetch_xor(&self, val: $int_type, order: Ordering) -> $int_type {
2500 // SAFETY: data races are prevented by atomic intrinsics.
2501 unsafe { atomic_xor(self.v.get(), val, order) }
2504 /// Fetches the value, and applies a function to it that returns an optional
2505 /// new value. Returns a `Result` of `Ok(previous_value)` if the function returned `Some(_)`, else
2506 /// `Err(previous_value)`.
2508 /// Note: This may call the function multiple times if the value has been changed from other threads in
2509 /// the meantime, as long as the function returns `Some(_)`, but the function will have been applied
2510 /// only once to the stored value.
2512 /// `fetch_update` takes two [`Ordering`] arguments to describe the memory ordering of this operation.
2513 /// The first describes the required ordering for when the operation finally succeeds while the second
2514 /// describes the required ordering for loads. These correspond to the success and failure orderings of
2515 #[doc = concat!("[`", stringify!($atomic_type), "::compare_exchange`]")]
2518 /// Using [`Acquire`] as success ordering makes the store part
2519 /// of this operation [`Relaxed`], and using [`Release`] makes the final successful load
2520 /// [`Relaxed`]. The (failed) load ordering can only be [`SeqCst`], [`Acquire`] or [`Relaxed`]
2521 /// and must be equivalent to or weaker than the success ordering.
2523 /// **Note**: This method is only available on platforms that support atomic operations on
2524 #[doc = concat!("[`", $s_int_type, "`].")]
2529 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2531 #[doc = concat!("let x = ", stringify!($atomic_type), "::new(7);")]
2532 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |_| None), Err(7));
2533 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(7));
2534 /// assert_eq!(x.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| Some(x + 1)), Ok(8));
2535 /// assert_eq!(x.load(Ordering::SeqCst), 9);
2538 #[stable(feature = "no_more_cas", since = "1.45.0")]
2540 pub fn fetch_update<F>(&self,
2541 set_order: Ordering,
2542 fetch_order: Ordering,
2543 mut f: F) -> Result<$int_type, $int_type>
2544 where F: FnMut($int_type) -> Option<$int_type> {
2545 let mut prev = self.load(fetch_order);
2546 while let Some(next) = f(prev) {
2547 match self.compare_exchange_weak(prev, next, set_order, fetch_order) {
2548 x @ Ok(_) => return x,
2549 Err(next_prev) => prev = next_prev
2555 /// Maximum with the current value.
2557 /// Finds the maximum of the current value and the argument `val`, and
2558 /// sets the new value to the result.
2560 /// Returns the previous value.
2562 /// `fetch_max` takes an [`Ordering`] argument which describes the memory ordering
2563 /// of this operation. All ordering modes are possible. Note that using
2564 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2565 /// using [`Release`] makes the load part [`Relaxed`].
2567 /// **Note**: This method is only available on platforms that support atomic operations on
2568 #[doc = concat!("[`", $s_int_type, "`].")]
2573 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2575 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
2576 /// assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23);
2577 /// assert_eq!(foo.load(Ordering::SeqCst), 42);
2580 /// If you want to obtain the maximum value in one step, you can use the following:
2583 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2585 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
2587 /// let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar);
2588 /// assert!(max_foo == 42);
2591 #[stable(feature = "atomic_min_max", since = "1.45.0")]
2593 pub fn fetch_max(&self, val: $int_type, order: Ordering) -> $int_type {
2594 // SAFETY: data races are prevented by atomic intrinsics.
2595 unsafe { $max_fn(self.v.get(), val, order) }
2598 /// Minimum with the current value.
2600 /// Finds the minimum of the current value and the argument `val`, and
2601 /// sets the new value to the result.
2603 /// Returns the previous value.
2605 /// `fetch_min` takes an [`Ordering`] argument which describes the memory ordering
2606 /// of this operation. All ordering modes are possible. Note that using
2607 /// [`Acquire`] makes the store part of this operation [`Relaxed`], and
2608 /// using [`Release`] makes the load part [`Relaxed`].
2610 /// **Note**: This method is only available on platforms that support atomic operations on
2611 #[doc = concat!("[`", $s_int_type, "`].")]
2616 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2618 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
2619 /// assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23);
2620 /// assert_eq!(foo.load(Ordering::Relaxed), 23);
2621 /// assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23);
2622 /// assert_eq!(foo.load(Ordering::Relaxed), 22);
2625 /// If you want to obtain the minimum value in one step, you can use the following:
2628 #[doc = concat!($extra_feature, "use std::sync::atomic::{", stringify!($atomic_type), ", Ordering};")]
2630 #[doc = concat!("let foo = ", stringify!($atomic_type), "::new(23);")]
2632 /// let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar);
2633 /// assert_eq!(min_foo, 12);
2636 #[stable(feature = "atomic_min_max", since = "1.45.0")]
2638 pub fn fetch_min(&self, val: $int_type, order: Ordering) -> $int_type {
2639 // SAFETY: data races are prevented by atomic intrinsics.
2640 unsafe { $min_fn(self.v.get(), val, order) }
2643 /// Returns a mutable pointer to the underlying integer.
2645 /// Doing non-atomic reads and writes on the resulting integer can be a data race.
2646 /// This method is mostly useful for FFI, where the function signature may use
2647 #[doc = concat!("`*mut ", stringify!($int_type), "` instead of `&", stringify!($atomic_type), "`.")]
2649 /// Returning an `*mut` pointer from a shared reference to this atomic is safe because the
2650 /// atomic types work with interior mutability. All modifications of an atomic change the value
2651 /// through a shared reference, and can do so safely as long as they use atomic operations. Any
2652 /// use of the returned raw pointer requires an `unsafe` block and still has to uphold the same
2653 /// restriction: operations on it must be atomic.
2657 /// ```ignore (extern-declaration)
2659 #[doc = concat!($extra_feature, "use std::sync::atomic::", stringify!($atomic_type), ";")]
2662 #[doc = concat!(" fn my_atomic_op(arg: *mut ", stringify!($int_type), ");")]
2665 #[doc = concat!("let mut atomic = ", stringify!($atomic_type), "::new(1);")]
2667 // SAFETY: Safe as long as `my_atomic_op` is atomic.
2669 /// my_atomic_op(atomic.as_mut_ptr());
2674 #[unstable(feature = "atomic_mut_ptr",
2675 reason = "recently added",
2677 pub fn as_mut_ptr(&self) -> *mut $int_type {
2684 #[cfg(target_has_atomic_load_store = "8")]
2686 cfg(target_has_atomic = "8"),
2687 cfg(target_has_atomic_equal_alignment = "8"),
2688 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2689 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2690 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2691 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2692 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2693 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2694 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2695 unstable(feature = "integer_atomics", issue = "99069"),
2696 cfg_attr(not(test), rustc_diagnostic_item = "AtomicI8"),
2699 atomic_min, atomic_max,
2702 i8 AtomicI8 ATOMIC_I8_INIT
2704 #[cfg(target_has_atomic_load_store = "8")]
2706 cfg(target_has_atomic = "8"),
2707 cfg(target_has_atomic_equal_alignment = "8"),
2708 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2709 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2710 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2711 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2712 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2713 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2714 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2715 unstable(feature = "integer_atomics", issue = "99069"),
2716 cfg_attr(not(test), rustc_diagnostic_item = "AtomicU8"),
2719 atomic_umin, atomic_umax,
2722 u8 AtomicU8 ATOMIC_U8_INIT
2724 #[cfg(target_has_atomic_load_store = "16")]
2726 cfg(target_has_atomic = "16"),
2727 cfg(target_has_atomic_equal_alignment = "16"),
2728 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2729 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2730 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2731 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2732 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2733 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2734 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2735 unstable(feature = "integer_atomics", issue = "99069"),
2736 cfg_attr(not(test), rustc_diagnostic_item = "AtomicI16"),
2739 atomic_min, atomic_max,
2741 "AtomicI16::new(0)",
2742 i16 AtomicI16 ATOMIC_I16_INIT
2744 #[cfg(target_has_atomic_load_store = "16")]
2746 cfg(target_has_atomic = "16"),
2747 cfg(target_has_atomic_equal_alignment = "16"),
2748 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2749 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2750 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2751 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2752 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2753 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2754 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2755 unstable(feature = "integer_atomics", issue = "99069"),
2756 cfg_attr(not(test), rustc_diagnostic_item = "AtomicU16"),
2759 atomic_umin, atomic_umax,
2761 "AtomicU16::new(0)",
2762 u16 AtomicU16 ATOMIC_U16_INIT
2764 #[cfg(target_has_atomic_load_store = "32")]
2766 cfg(target_has_atomic = "32"),
2767 cfg(target_has_atomic_equal_alignment = "32"),
2768 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2769 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2770 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2771 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2772 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2773 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2774 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2775 unstable(feature = "integer_atomics", issue = "99069"),
2776 cfg_attr(not(test), rustc_diagnostic_item = "AtomicI32"),
2779 atomic_min, atomic_max,
2781 "AtomicI32::new(0)",
2782 i32 AtomicI32 ATOMIC_I32_INIT
2784 #[cfg(target_has_atomic_load_store = "32")]
2786 cfg(target_has_atomic = "32"),
2787 cfg(target_has_atomic_equal_alignment = "32"),
2788 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2789 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2790 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2791 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2792 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2793 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2794 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2795 unstable(feature = "integer_atomics", issue = "99069"),
2796 cfg_attr(not(test), rustc_diagnostic_item = "AtomicU32"),
2799 atomic_umin, atomic_umax,
2801 "AtomicU32::new(0)",
2802 u32 AtomicU32 ATOMIC_U32_INIT
2804 #[cfg(target_has_atomic_load_store = "64")]
2806 cfg(target_has_atomic = "64"),
2807 cfg(target_has_atomic_equal_alignment = "64"),
2808 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2809 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2810 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2811 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2812 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2813 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2814 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2815 unstable(feature = "integer_atomics", issue = "99069"),
2816 cfg_attr(not(test), rustc_diagnostic_item = "AtomicI64"),
2819 atomic_min, atomic_max,
2821 "AtomicI64::new(0)",
2822 i64 AtomicI64 ATOMIC_I64_INIT
2824 #[cfg(target_has_atomic_load_store = "64")]
2826 cfg(target_has_atomic = "64"),
2827 cfg(target_has_atomic_equal_alignment = "64"),
2828 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2829 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2830 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2831 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2832 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2833 stable(feature = "integer_atomics_stable", since = "1.34.0"),
2834 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2835 unstable(feature = "integer_atomics", issue = "99069"),
2836 cfg_attr(not(test), rustc_diagnostic_item = "AtomicU64"),
2839 atomic_umin, atomic_umax,
2841 "AtomicU64::new(0)",
2842 u64 AtomicU64 ATOMIC_U64_INIT
2844 #[cfg(target_has_atomic_load_store = "128")]
2846 cfg(target_has_atomic = "128"),
2847 cfg(target_has_atomic_equal_alignment = "128"),
2848 unstable(feature = "integer_atomics", issue = "99069"),
2849 unstable(feature = "integer_atomics", issue = "99069"),
2850 unstable(feature = "integer_atomics", issue = "99069"),
2851 unstable(feature = "integer_atomics", issue = "99069"),
2852 unstable(feature = "integer_atomics", issue = "99069"),
2853 unstable(feature = "integer_atomics", issue = "99069"),
2854 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2855 unstable(feature = "integer_atomics", issue = "99069"),
2856 cfg_attr(not(test), rustc_diagnostic_item = "AtomicI128"),
2858 "#![feature(integer_atomics)]\n\n",
2859 atomic_min, atomic_max,
2861 "AtomicI128::new(0)",
2862 i128 AtomicI128 ATOMIC_I128_INIT
2864 #[cfg(target_has_atomic_load_store = "128")]
2866 cfg(target_has_atomic = "128"),
2867 cfg(target_has_atomic_equal_alignment = "128"),
2868 unstable(feature = "integer_atomics", issue = "99069"),
2869 unstable(feature = "integer_atomics", issue = "99069"),
2870 unstable(feature = "integer_atomics", issue = "99069"),
2871 unstable(feature = "integer_atomics", issue = "99069"),
2872 unstable(feature = "integer_atomics", issue = "99069"),
2873 unstable(feature = "integer_atomics", issue = "99069"),
2874 rustc_const_stable(feature = "const_integer_atomics", since = "1.34.0"),
2875 unstable(feature = "integer_atomics", issue = "99069"),
2876 cfg_attr(not(test), rustc_diagnostic_item = "AtomicU128"),
2878 "#![feature(integer_atomics)]\n\n",
2879 atomic_umin, atomic_umax,
2881 "AtomicU128::new(0)",
2882 u128 AtomicU128 ATOMIC_U128_INIT
2885 macro_rules! atomic_int_ptr_sized {
2886 ( $($target_pointer_width:literal $align:literal)* ) => { $(
2887 #[cfg(target_has_atomic_load_store = "ptr")]
2888 #[cfg(target_pointer_width = $target_pointer_width)]
2890 cfg(target_has_atomic = "ptr"),
2891 cfg(target_has_atomic_equal_alignment = "ptr"),
2892 stable(feature = "rust1", since = "1.0.0"),
2893 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
2894 stable(feature = "atomic_debug", since = "1.3.0"),
2895 stable(feature = "atomic_access", since = "1.15.0"),
2896 stable(feature = "atomic_from", since = "1.23.0"),
2897 stable(feature = "atomic_nand", since = "1.27.0"),
2898 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
2899 stable(feature = "rust1", since = "1.0.0"),
2900 cfg_attr(not(test), rustc_diagnostic_item = "AtomicIsize"),
2903 atomic_min, atomic_max,
2905 "AtomicIsize::new(0)",
2906 isize AtomicIsize ATOMIC_ISIZE_INIT
2908 #[cfg(target_has_atomic_load_store = "ptr")]
2909 #[cfg(target_pointer_width = $target_pointer_width)]
2911 cfg(target_has_atomic = "ptr"),
2912 cfg(target_has_atomic_equal_alignment = "ptr"),
2913 stable(feature = "rust1", since = "1.0.0"),
2914 stable(feature = "extended_compare_and_swap", since = "1.10.0"),
2915 stable(feature = "atomic_debug", since = "1.3.0"),
2916 stable(feature = "atomic_access", since = "1.15.0"),
2917 stable(feature = "atomic_from", since = "1.23.0"),
2918 stable(feature = "atomic_nand", since = "1.27.0"),
2919 rustc_const_stable(feature = "const_ptr_sized_atomics", since = "1.24.0"),
2920 stable(feature = "rust1", since = "1.0.0"),
2921 cfg_attr(not(test), rustc_diagnostic_item = "AtomicUsize"),
2924 atomic_umin, atomic_umax,
2926 "AtomicUsize::new(0)",
2927 usize AtomicUsize ATOMIC_USIZE_INIT
2932 atomic_int_ptr_sized! {
2939 #[cfg(target_has_atomic = "8")]
2940 fn strongest_failure_ordering(order: Ordering) -> Ordering {
2951 unsafe fn atomic_store<T: Copy>(dst: *mut T, val: T, order: Ordering) {
2952 // SAFETY: the caller must uphold the safety contract for `atomic_store`.
2955 Relaxed => intrinsics::atomic_store_relaxed(dst, val),
2956 Release => intrinsics::atomic_store_release(dst, val),
2957 SeqCst => intrinsics::atomic_store_seqcst(dst, val),
2958 Acquire => panic!("there is no such thing as an acquire store"),
2959 AcqRel => panic!("there is no such thing as an acquire-release store"),
2965 unsafe fn atomic_load<T: Copy>(dst: *const T, order: Ordering) -> T {
2966 // SAFETY: the caller must uphold the safety contract for `atomic_load`.
2969 Relaxed => intrinsics::atomic_load_relaxed(dst),
2970 Acquire => intrinsics::atomic_load_acquire(dst),
2971 SeqCst => intrinsics::atomic_load_seqcst(dst),
2972 Release => panic!("there is no such thing as a release load"),
2973 AcqRel => panic!("there is no such thing as an acquire-release load"),
2979 #[cfg(target_has_atomic = "8")]
2980 unsafe fn atomic_swap<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
2981 // SAFETY: the caller must uphold the safety contract for `atomic_swap`.
2984 Relaxed => intrinsics::atomic_xchg_relaxed(dst, val),
2985 Acquire => intrinsics::atomic_xchg_acquire(dst, val),
2986 Release => intrinsics::atomic_xchg_release(dst, val),
2987 AcqRel => intrinsics::atomic_xchg_acqrel(dst, val),
2988 SeqCst => intrinsics::atomic_xchg_seqcst(dst, val),
2993 /// Returns the previous value (like __sync_fetch_and_add).
2995 #[cfg(target_has_atomic = "8")]
2996 unsafe fn atomic_add<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
2997 // SAFETY: the caller must uphold the safety contract for `atomic_add`.
3000 Relaxed => intrinsics::atomic_xadd_relaxed(dst, val),
3001 Acquire => intrinsics::atomic_xadd_acquire(dst, val),
3002 Release => intrinsics::atomic_xadd_release(dst, val),
3003 AcqRel => intrinsics::atomic_xadd_acqrel(dst, val),
3004 SeqCst => intrinsics::atomic_xadd_seqcst(dst, val),
3009 /// Returns the previous value (like __sync_fetch_and_sub).
3011 #[cfg(target_has_atomic = "8")]
3012 unsafe fn atomic_sub<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3013 // SAFETY: the caller must uphold the safety contract for `atomic_sub`.
3016 Relaxed => intrinsics::atomic_xsub_relaxed(dst, val),
3017 Acquire => intrinsics::atomic_xsub_acquire(dst, val),
3018 Release => intrinsics::atomic_xsub_release(dst, val),
3019 AcqRel => intrinsics::atomic_xsub_acqrel(dst, val),
3020 SeqCst => intrinsics::atomic_xsub_seqcst(dst, val),
3026 #[cfg(target_has_atomic = "8")]
3027 unsafe fn atomic_compare_exchange<T: Copy>(
3034 // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange`.
3035 let (val, ok) = unsafe {
3036 match (success, failure) {
3037 (Relaxed, Relaxed) => intrinsics::atomic_cxchg_relaxed_relaxed(dst, old, new),
3038 //(Relaxed, Acquire) => intrinsics::atomic_cxchg_relaxed_acquire(dst, old, new),
3039 //(Relaxed, SeqCst) => intrinsics::atomic_cxchg_relaxed_seqcst(dst, old, new),
3040 (Acquire, Relaxed) => intrinsics::atomic_cxchg_acquire_relaxed(dst, old, new),
3041 (Acquire, Acquire) => intrinsics::atomic_cxchg_acquire_acquire(dst, old, new),
3042 //(Acquire, SeqCst) => intrinsics::atomic_cxchg_acquire_seqcst(dst, old, new),
3043 (Release, Relaxed) => intrinsics::atomic_cxchg_release_relaxed(dst, old, new),
3044 //(Release, Acquire) => intrinsics::atomic_cxchg_release_acquire(dst, old, new),
3045 //(Release, SeqCst) => intrinsics::atomic_cxchg_release_seqcst(dst, old, new),
3046 (AcqRel, Relaxed) => intrinsics::atomic_cxchg_acqrel_relaxed(dst, old, new),
3047 (AcqRel, Acquire) => intrinsics::atomic_cxchg_acqrel_acquire(dst, old, new),
3048 //(AcqRel, SeqCst) => intrinsics::atomic_cxchg_acqrel_seqcst(dst, old, new),
3049 (SeqCst, Relaxed) => intrinsics::atomic_cxchg_seqcst_relaxed(dst, old, new),
3050 (SeqCst, Acquire) => intrinsics::atomic_cxchg_seqcst_acquire(dst, old, new),
3051 (SeqCst, SeqCst) => intrinsics::atomic_cxchg_seqcst_seqcst(dst, old, new),
3052 (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
3053 (_, Release) => panic!("there is no such thing as a release failure ordering"),
3054 _ => panic!("a failure ordering can't be stronger than a success ordering"),
3057 if ok { Ok(val) } else { Err(val) }
3061 #[cfg(target_has_atomic = "8")]
3062 unsafe fn atomic_compare_exchange_weak<T: Copy>(
3069 // SAFETY: the caller must uphold the safety contract for `atomic_compare_exchange_weak`.
3070 let (val, ok) = unsafe {
3071 match (success, failure) {
3072 (Relaxed, Relaxed) => intrinsics::atomic_cxchgweak_relaxed_relaxed(dst, old, new),
3073 //(Relaxed, Acquire) => intrinsics::atomic_cxchgweak_relaxed_acquire(dst, old, new),
3074 //(Relaxed, SeqCst) => intrinsics::atomic_cxchgweak_relaxed_seqcst(dst, old, new),
3075 (Acquire, Relaxed) => intrinsics::atomic_cxchgweak_acquire_relaxed(dst, old, new),
3076 (Acquire, Acquire) => intrinsics::atomic_cxchgweak_acquire_acquire(dst, old, new),
3077 //(Acquire, SeqCst) => intrinsics::atomic_cxchgweak_acquire_seqcst(dst, old, new),
3078 (Release, Relaxed) => intrinsics::atomic_cxchgweak_release_relaxed(dst, old, new),
3079 //(Release, Acquire) => intrinsics::atomic_cxchgweak_release_acquire(dst, old, new),
3080 //(Release, SeqCst) => intrinsics::atomic_cxchgweak_release_seqcst(dst, old, new),
3081 (AcqRel, Relaxed) => intrinsics::atomic_cxchgweak_acqrel_relaxed(dst, old, new),
3082 (AcqRel, Acquire) => intrinsics::atomic_cxchgweak_acqrel_acquire(dst, old, new),
3083 //(AcqRel, SeqCst) => intrinsics::atomic_cxchgweak_acqrel_seqcst(dst, old, new),
3084 (SeqCst, Relaxed) => intrinsics::atomic_cxchgweak_seqcst_relaxed(dst, old, new),
3085 (SeqCst, Acquire) => intrinsics::atomic_cxchgweak_seqcst_acquire(dst, old, new),
3086 (SeqCst, SeqCst) => intrinsics::atomic_cxchgweak_seqcst_seqcst(dst, old, new),
3087 (_, AcqRel) => panic!("there is no such thing as an acquire-release failure ordering"),
3088 (_, Release) => panic!("there is no such thing as a release failure ordering"),
3089 _ => panic!("a failure ordering can't be stronger than a success ordering"),
3092 if ok { Ok(val) } else { Err(val) }
3096 #[cfg(target_has_atomic = "8")]
3097 unsafe fn atomic_and<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3098 // SAFETY: the caller must uphold the safety contract for `atomic_and`
3101 Relaxed => intrinsics::atomic_and_relaxed(dst, val),
3102 Acquire => intrinsics::atomic_and_acquire(dst, val),
3103 Release => intrinsics::atomic_and_release(dst, val),
3104 AcqRel => intrinsics::atomic_and_acqrel(dst, val),
3105 SeqCst => intrinsics::atomic_and_seqcst(dst, val),
3111 #[cfg(target_has_atomic = "8")]
3112 unsafe fn atomic_nand<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3113 // SAFETY: the caller must uphold the safety contract for `atomic_nand`
3116 Relaxed => intrinsics::atomic_nand_relaxed(dst, val),
3117 Acquire => intrinsics::atomic_nand_acquire(dst, val),
3118 Release => intrinsics::atomic_nand_release(dst, val),
3119 AcqRel => intrinsics::atomic_nand_acqrel(dst, val),
3120 SeqCst => intrinsics::atomic_nand_seqcst(dst, val),
3126 #[cfg(target_has_atomic = "8")]
3127 unsafe fn atomic_or<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3128 // SAFETY: the caller must uphold the safety contract for `atomic_or`
3131 SeqCst => intrinsics::atomic_or_seqcst(dst, val),
3132 Acquire => intrinsics::atomic_or_acquire(dst, val),
3133 Release => intrinsics::atomic_or_release(dst, val),
3134 AcqRel => intrinsics::atomic_or_acqrel(dst, val),
3135 Relaxed => intrinsics::atomic_or_relaxed(dst, val),
3141 #[cfg(target_has_atomic = "8")]
3142 unsafe fn atomic_xor<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3143 // SAFETY: the caller must uphold the safety contract for `atomic_xor`
3146 SeqCst => intrinsics::atomic_xor_seqcst(dst, val),
3147 Acquire => intrinsics::atomic_xor_acquire(dst, val),
3148 Release => intrinsics::atomic_xor_release(dst, val),
3149 AcqRel => intrinsics::atomic_xor_acqrel(dst, val),
3150 Relaxed => intrinsics::atomic_xor_relaxed(dst, val),
3155 /// returns the max value (signed comparison)
3157 #[cfg(target_has_atomic = "8")]
3158 unsafe fn atomic_max<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3159 // SAFETY: the caller must uphold the safety contract for `atomic_max`
3162 Relaxed => intrinsics::atomic_max_relaxed(dst, val),
3163 Acquire => intrinsics::atomic_max_acquire(dst, val),
3164 Release => intrinsics::atomic_max_release(dst, val),
3165 AcqRel => intrinsics::atomic_max_acqrel(dst, val),
3166 SeqCst => intrinsics::atomic_max_seqcst(dst, val),
3171 /// returns the min value (signed comparison)
3173 #[cfg(target_has_atomic = "8")]
3174 unsafe fn atomic_min<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3175 // SAFETY: the caller must uphold the safety contract for `atomic_min`
3178 Relaxed => intrinsics::atomic_min_relaxed(dst, val),
3179 Acquire => intrinsics::atomic_min_acquire(dst, val),
3180 Release => intrinsics::atomic_min_release(dst, val),
3181 AcqRel => intrinsics::atomic_min_acqrel(dst, val),
3182 SeqCst => intrinsics::atomic_min_seqcst(dst, val),
3187 /// returns the max value (unsigned comparison)
3189 #[cfg(target_has_atomic = "8")]
3190 unsafe fn atomic_umax<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3191 // SAFETY: the caller must uphold the safety contract for `atomic_umax`
3194 Relaxed => intrinsics::atomic_umax_relaxed(dst, val),
3195 Acquire => intrinsics::atomic_umax_acquire(dst, val),
3196 Release => intrinsics::atomic_umax_release(dst, val),
3197 AcqRel => intrinsics::atomic_umax_acqrel(dst, val),
3198 SeqCst => intrinsics::atomic_umax_seqcst(dst, val),
3203 /// returns the min value (unsigned comparison)
3205 #[cfg(target_has_atomic = "8")]
3206 unsafe fn atomic_umin<T: Copy>(dst: *mut T, val: T, order: Ordering) -> T {
3207 // SAFETY: the caller must uphold the safety contract for `atomic_umin`
3210 Relaxed => intrinsics::atomic_umin_relaxed(dst, val),
3211 Acquire => intrinsics::atomic_umin_acquire(dst, val),
3212 Release => intrinsics::atomic_umin_release(dst, val),
3213 AcqRel => intrinsics::atomic_umin_acqrel(dst, val),
3214 SeqCst => intrinsics::atomic_umin_seqcst(dst, val),
3219 /// An atomic fence.
3221 /// Depending on the specified order, a fence prevents the compiler and CPU from
3222 /// reordering certain types of memory operations around it.
3223 /// That creates synchronizes-with relationships between it and atomic operations
3224 /// or fences in other threads.
3226 /// A fence 'A' which has (at least) [`Release`] ordering semantics, synchronizes
3227 /// with a fence 'B' with (at least) [`Acquire`] semantics, if and only if there
3228 /// exist operations X and Y, both operating on some atomic object 'M' such
3229 /// that A is sequenced before X, Y is sequenced before B and Y observes
3230 /// the change to M. This provides a happens-before dependence between A and B.
3233 /// Thread 1 Thread 2
3235 /// fence(Release); A --------------
3236 /// x.store(3, Relaxed); X --------- |
3239 /// -------------> Y if x.load(Relaxed) == 3 {
3240 /// |-------> B fence(Acquire);
3245 /// Atomic operations with [`Release`] or [`Acquire`] semantics can also synchronize
3248 /// A fence which has [`SeqCst`] ordering, in addition to having both [`Acquire`]
3249 /// and [`Release`] semantics, participates in the global program order of the
3250 /// other [`SeqCst`] operations and/or fences.
3252 /// Accepts [`Acquire`], [`Release`], [`AcqRel`] and [`SeqCst`] orderings.
3256 /// Panics if `order` is [`Relaxed`].
3261 /// use std::sync::atomic::AtomicBool;
3262 /// use std::sync::atomic::fence;
3263 /// use std::sync::atomic::Ordering;
3265 /// // A mutual exclusion primitive based on spinlock.
3266 /// pub struct Mutex {
3267 /// flag: AtomicBool,
3271 /// pub fn new() -> Mutex {
3273 /// flag: AtomicBool::new(false),
3277 /// pub fn lock(&self) {
3278 /// // Wait until the old value is `false`.
3281 /// .compare_exchange_weak(false, true, Ordering::Relaxed, Ordering::Relaxed)
3284 /// // This fence synchronizes-with store in `unlock`.
3285 /// fence(Ordering::Acquire);
3288 /// pub fn unlock(&self) {
3289 /// self.flag.store(false, Ordering::Release);
3294 #[stable(feature = "rust1", since = "1.0.0")]
3295 #[rustc_diagnostic_item = "fence"]
3296 pub fn fence(order: Ordering) {
3297 // SAFETY: using an atomic fence is safe.
3300 Acquire => intrinsics::atomic_fence_acquire(),
3301 Release => intrinsics::atomic_fence_release(),
3302 AcqRel => intrinsics::atomic_fence_acqrel(),
3303 SeqCst => intrinsics::atomic_fence_seqcst(),
3304 Relaxed => panic!("there is no such thing as a relaxed fence"),
3309 /// A compiler memory fence.
3311 /// `compiler_fence` does not emit any machine code, but restricts the kinds
3312 /// of memory re-ordering the compiler is allowed to do. Specifically, depending on
3313 /// the given [`Ordering`] semantics, the compiler may be disallowed from moving reads
3314 /// or writes from before or after the call to the other side of the call to
3315 /// `compiler_fence`. Note that it does **not** prevent the *hardware*
3316 /// from doing such re-ordering. This is not a problem in a single-threaded,
3317 /// execution context, but when other threads may modify memory at the same
3318 /// time, stronger synchronization primitives such as [`fence`] are required.
3320 /// The re-ordering prevented by the different ordering semantics are:
3322 /// - with [`SeqCst`], no re-ordering of reads and writes across this point is allowed.
3323 /// - with [`Release`], preceding reads and writes cannot be moved past subsequent writes.
3324 /// - with [`Acquire`], subsequent reads and writes cannot be moved ahead of preceding reads.
3325 /// - with [`AcqRel`], both of the above rules are enforced.
3327 /// `compiler_fence` is generally only useful for preventing a thread from
3328 /// racing *with itself*. That is, if a given thread is executing one piece
3329 /// of code, and is then interrupted, and starts executing code elsewhere
3330 /// (while still in the same thread, and conceptually still on the same
3331 /// core). In traditional programs, this can only occur when a signal
3332 /// handler is registered. In more low-level code, such situations can also
3333 /// arise when handling interrupts, when implementing green threads with
3334 /// pre-emption, etc. Curious readers are encouraged to read the Linux kernel's
3335 /// discussion of [memory barriers].
3339 /// Panics if `order` is [`Relaxed`].
3343 /// Without `compiler_fence`, the `assert_eq!` in following code
3344 /// is *not* guaranteed to succeed, despite everything happening in a single thread.
3345 /// To see why, remember that the compiler is free to swap the stores to
3346 /// `IMPORTANT_VARIABLE` and `IS_READY` since they are both
3347 /// `Ordering::Relaxed`. If it does, and the signal handler is invoked right
3348 /// after `IS_READY` is updated, then the signal handler will see
3349 /// `IS_READY=1`, but `IMPORTANT_VARIABLE=0`.
3350 /// Using a `compiler_fence` remedies this situation.
3353 /// use std::sync::atomic::{AtomicBool, AtomicUsize};
3354 /// use std::sync::atomic::Ordering;
3355 /// use std::sync::atomic::compiler_fence;
3357 /// static IMPORTANT_VARIABLE: AtomicUsize = AtomicUsize::new(0);
3358 /// static IS_READY: AtomicBool = AtomicBool::new(false);
3361 /// IMPORTANT_VARIABLE.store(42, Ordering::Relaxed);
3362 /// // prevent earlier writes from being moved beyond this point
3363 /// compiler_fence(Ordering::Release);
3364 /// IS_READY.store(true, Ordering::Relaxed);
3367 /// fn signal_handler() {
3368 /// if IS_READY.load(Ordering::Relaxed) {
3369 /// assert_eq!(IMPORTANT_VARIABLE.load(Ordering::Relaxed), 42);
3374 /// [memory barriers]: https://www.kernel.org/doc/Documentation/memory-barriers.txt
3376 #[stable(feature = "compiler_fences", since = "1.21.0")]
3377 #[rustc_diagnostic_item = "compiler_fence"]
3378 pub fn compiler_fence(order: Ordering) {
3379 // SAFETY: using an atomic fence is safe.
3382 Acquire => intrinsics::atomic_singlethreadfence_acquire(),
3383 Release => intrinsics::atomic_singlethreadfence_release(),
3384 AcqRel => intrinsics::atomic_singlethreadfence_acqrel(),
3385 SeqCst => intrinsics::atomic_singlethreadfence_seqcst(),
3386 Relaxed => panic!("there is no such thing as a relaxed compiler fence"),
3391 #[cfg(target_has_atomic_load_store = "8")]
3392 #[stable(feature = "atomic_debug", since = "1.3.0")]
3393 impl fmt::Debug for AtomicBool {
3394 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3395 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
3399 #[cfg(target_has_atomic_load_store = "ptr")]
3400 #[stable(feature = "atomic_debug", since = "1.3.0")]
3401 impl<T> fmt::Debug for AtomicPtr<T> {
3402 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3403 fmt::Debug::fmt(&self.load(Ordering::Relaxed), f)
3407 #[cfg(target_has_atomic_load_store = "ptr")]
3408 #[stable(feature = "atomic_pointer", since = "1.24.0")]
3409 impl<T> fmt::Pointer for AtomicPtr<T> {
3410 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3411 fmt::Pointer::fmt(&self.load(Ordering::SeqCst), f)
3415 /// Signals the processor that it is inside a busy-wait spin-loop ("spin lock").
3417 /// This function is deprecated in favor of [`hint::spin_loop`].
3419 /// [`hint::spin_loop`]: crate::hint::spin_loop
3421 #[stable(feature = "spin_loop_hint", since = "1.24.0")]
3422 #[deprecated(since = "1.51.0", note = "use hint::spin_loop instead")]
3423 pub fn spin_loop_hint() {