Struct Atomic
#[repr(C)]
pub struct Atomic<T: AtomicPrimitive> { pub(in ::sync::atomic) v: UnsafeCell<T::Storage> }
A memory location which can be safely modified from multiple threads.
This has the same size and bit validity as the underlying type T. However,
the alignment of this type is always equal to its size, even on targets where
T has alignment less than its size.
For more about the differences between atomic types and non-atomic types as well as information about the portability of this type, please see the module-level documentation.
Note: This type is only available on platforms that support atomic loads
and stores of T.
Fields
v: UnsafeCell<T::Storage>
Implementations
impl Atomic<bool>
const fn new(v: bool) -> AtomicBoolCreates a new
AtomicBool.Examples
use AtomicBool; let atomic_true = new; let atomic_false = new;const unsafe fn from_ptr<'a>(ptr: *mut bool) -> &'a AtomicBoolCreates a new
AtomicBoolfrom a pointer.Examples
use ; // Get a pointer to an allocated value let ptr: *mut bool = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicBool>()(note that this is always true, sincealign_of::<AtomicBool>() == 1).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut bool) -> *const AtomicBoolCreates a new pointer to
AtomicBoolfrom a pointer.This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut boolReturns a mutable reference to the underlying
bool.This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_bool = new; assert_eq!; *some_bool.get_mut = false; assert_eq!;const fn from_mut(v: &mut bool) -> &mut SelfGets atomic access to a
&mut bool.Examples
use ; let mut some_bool = true; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [bool]Gets non-atomic access to a
&mut [AtomicBool]slice.This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicBool, Ordering}; let mut some_bools = [const { AtomicBool::new(false) }; 10]; let view: &mut [bool] = AtomicBool::get_mut_slice(&mut some_bools); assert_eq!(view, [false; 10]); view[..5].copy_from_slice(&[true; 5]); std::thread::scope(|s| { for t in &some_bools[..5] { s.spawn(move || assert_eq!(t.load(Ordering::Relaxed), true)); } for f in &some_bools[5..] { s.spawn(move || assert_eq!(f.load(Ordering::Relaxed), false)); } });const fn from_mut_slice(v: &mut [bool]) -> &mut [Self]Gets atomic access to a
&mut [bool]slice.Examples
use ; let mut some_bools = ; let a = &*from_mut_slice; scope; assert_eq!;const fn into_inner(self) -> boolConsumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicBool; let some_bool = new; assert_eq!;const fn load(&self, order: Ordering) -> boolLoads a value from the bool.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_bool = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> boolPerform a volatile atomic load from the bool.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
Reading from
selfmust produce a properly initialized value of typebool.
Panics
-
const fn store(&self, val: bool, order: Ordering)Stores a value into the bool.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_bool = new; some_bool.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: bool, order: Ordering)Performs a volatile atomic store into the bool.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
Panics
-
const fn swap(&self, val: bool, order: Ordering) -> boolStores a value into the bool, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let some_bool = new; assert_eq!; assert_eq!;const fn compare_and_swap(&self, current: bool, new: bool, order: Ordering) -> boolStores a value into the
boolif the current value is the same as thecurrentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_bool = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: bool, new: bool, success: Ordering, failure: Ordering) -> Result<bool, bool>Stores a value into the
boolif the current value is the same as thecurrentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let some_bool = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: bool, new: bool, success: Ordering, failure: Ordering) -> Result<bool, bool>Stores a value into the
boolif the current value is the same as thecurrentvalue.Unlike
AtomicBool::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let val = new; let new = true; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. In this case,compare_exchangecan lead to the ABA problem.const fn fetch_and(&self, val: bool, order: Ordering) -> boolLogical "and" with a boolean value.
Performs a logical "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: bool, order: Ordering) -> boolLogical "nand" with a boolean value.
Performs a logical "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: bool, order: Ordering) -> boolLogical "or" with a boolean value.
Performs a logical "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: bool, order: Ordering) -> boolLogical "xor" with a boolean value.
Performs a logical "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;const fn fetch_not(&self, order: Ordering) -> boolLogical "not" with a boolean value.
Performs a logical "not" operation on the current value, and sets the new value to the result.
Returns the previous value.
fetch_nottakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;const fn as_ptr(&self) -> *mut boolReturns a mutable pointer to the underlying
bool.Doing non-atomic reads and writes on the resulting boolean can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut boolinstead of&AtomicBool.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicBool; extern "C" { fn my_atomic_op(arg: *mut bool); } let mut atomic = AtomicBool::new(true); unsafe { my_atomic_op(atomic.as_ptr()); } # }fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<bool, bool> where F: FnMut(bool) -> Option<bool>,An alias for
AtomicBool::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(bool) -> Option<bool>) -> Result<bool, bool>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicBool::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(bool) -> bool) -> boolFetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicBool::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;
impl Atomic<i128>
const fn new(v: i128) -> SelfCreates a new atomic integer.
Examples
#![feature(integer_atomics)] use std::sync::atomic::AtomicI128; let atomic_forty_two = AtomicI128::new(42);const unsafe fn from_ptr<'a>(ptr: *mut i128) -> &'a AtomicI128Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut i128 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicI128>()(note that on some platforms this can be bigger thanalign_of::<i128>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut i128) -> *const AtomicI128Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut i128Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let mut some_var = AtomicI128::new(10); assert_eq!(*some_var.get_mut(), 10); *some_var.get_mut() = 5; assert_eq!(some_var.load(Ordering::SeqCst), 5);const fn from_mut(v: &mut i128) -> &mut SelfGet atomic access to a
&mut i128.Note: This function is only available on targets where
AtomicI128has the same alignment asi128.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [i128]Get non-atomic access to a
&mut [AtomicI128]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let mut some_ints = [const { AtomicI128::new(0) }; 10]; let view: &mut [i128] = AtomicI128::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [i128]) -> &mut [Self]Get atomic access to a
&mut [i128]slice.Note: This function is only available on targets where
AtomicI128has the same alignment asi128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicI128::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> i128Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
#![feature(integer_atomics)] use std::sync::atomic::AtomicI128; let some_var = AtomicI128::new(5); assert_eq!(some_var.into_inner(), 5);const fn load(&self, order: Ordering) -> i128Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let some_var = AtomicI128::new(5); assert_eq!(some_var.load(Ordering::Relaxed), 5);const unsafe fn load_volatile(self: *const Self, order: Ordering) -> i128Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI128>()(note that on some platforms this can be bigger thanalign_of::<i128>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: i128, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let some_var = AtomicI128::new(5); some_var.store(10, Ordering::Relaxed); assert_eq!(some_var.load(Ordering::Relaxed), 10);const unsafe fn store_volatile(self: *const Self, val: i128, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI128>()(note that on some platforms this can be bigger thanalign_of::<i128>()).
Panics
-
const fn swap(&self, val: i128, order: Ordering) -> i128Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let some_var = AtomicI128::new(5); assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);const fn compare_and_swap(&self, current: i128, new: i128, order: Ordering) -> i128Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let some_var = AtomicI128::new(5); assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5); assert_eq!(some_var.load(Ordering::Relaxed), 10); assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10); assert_eq!(some_var.load(Ordering::Relaxed), 10);const fn compare_exchange(&self, current: i128, new: i128, success: Ordering, failure: Ordering) -> Result<i128, i128>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let some_var = AtomicI128::new(5); assert_eq!(some_var.compare_exchange(5, 10, Ordering::Acquire, Ordering::Relaxed), Ok(5)); assert_eq!(some_var.load(Ordering::Relaxed), 10); assert_eq!(some_var.compare_exchange(6, 12, Ordering::SeqCst, Ordering::Acquire), Err(10)); assert_eq!(some_var.load(Ordering::Relaxed), 10);Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: i128, new: i128, success: Ordering, failure: Ordering) -> Result<i128, i128>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicI128::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let val = AtomicI128::new(4); let mut old = val.load(Ordering::Relaxed); loop { let new = old * 2; match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) { Ok(_) => break, Err(x) => old = x, } }Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: i128, order: Ordering) -> i128Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(0); assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0); assert_eq!(foo.load(Ordering::SeqCst), 10);const fn fetch_sub(&self, val: i128, order: Ordering) -> i128Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(20); assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20); assert_eq!(foo.load(Ordering::SeqCst), 10);const fn fetch_and(&self, val: i128, order: Ordering) -> i128Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(0b101101); assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101); assert_eq!(foo.load(Ordering::SeqCst), 0b100001);const fn fetch_nand(&self, val: i128, order: Ordering) -> i128Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(0x13); assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13); assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));const fn fetch_or(&self, val: i128, order: Ordering) -> i128Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(0b101101); assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101); assert_eq!(foo.load(Ordering::SeqCst), 0b111111);const fn fetch_xor(&self, val: i128, order: Ordering) -> i128Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(0b101101); assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101); assert_eq!(foo.load(Ordering::SeqCst), 0b011110);fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<i128, i128> where F: FnMut(i128) -> Option<i128>,An alias for
AtomicI128::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i128) -> Option<i128>) -> Result<i128, i128>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI128::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i128) -> i128) -> i128Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI128::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: i128, order: Ordering) -> i128Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(23); assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23); assert_eq!(foo.load(Ordering::SeqCst), 42);If you want to obtain the maximum value in one step, you can use the following:
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(23); let bar = 42; let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar); assert!(max_foo == 42);const fn fetch_min(&self, val: i128, order: Ordering) -> i128Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(23); assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23); assert_eq!(foo.load(Ordering::Relaxed), 23); assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23); assert_eq!(foo.load(Ordering::Relaxed), 22);If you want to obtain the minimum value in one step, you can use the following:
#![feature(integer_atomics)] use std::sync::atomic::{AtomicI128, Ordering}; let foo = AtomicI128::new(23); let bar = 12; let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar); assert_eq!(min_foo, 12);const fn as_ptr(&self) -> *mut i128Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut i128instead of&AtomicI128.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { #![feature(integer_atomics)] use std::sync::atomic::AtomicI128; extern "C" { fn my_atomic_op(arg: *mut i128); } let atomic = AtomicI128::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<i16>
const fn new(v: i16) -> SelfCreates a new atomic integer.
Examples
use AtomicI16; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut i16) -> &'a AtomicI16Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut i16 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicI16>()(note that on some platforms this can be bigger thanalign_of::<i16>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut i16) -> *const AtomicI16Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut i16Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut i16) -> &mut SelfGet atomic access to a
&mut i16.Note: This function is only available on targets where
AtomicI16has the same alignment asi16.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [i16]Get non-atomic access to a
&mut [AtomicI16]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicI16, Ordering}; let mut some_ints = [const { AtomicI16::new(0) }; 10]; let view: &mut [i16] = AtomicI16::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [i16]) -> &mut [Self]Get atomic access to a
&mut [i16]slice.Note: This function is only available on targets where
AtomicI16has the same alignment asi16.Examples
use std::sync::atomic::{AtomicI16, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicI16::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> i16Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicI16; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> i16Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> i16Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI16>()(note that on some platforms this can be bigger thanalign_of::<i16>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: i16, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: i16, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI16>()(note that on some platforms this can be bigger thanalign_of::<i16>()).
Panics
-
const fn swap(&self, val: i16, order: Ordering) -> i16Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: i16, new: i16, order: Ordering) -> i16Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: i16, new: i16, success: Ordering, failure: Ordering) -> Result<i16, i16>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: i16, new: i16, success: Ordering, failure: Ordering) -> Result<i16, i16>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicI16::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: i16, order: Ordering) -> i16Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: i16, order: Ordering) -> i16Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: i16, order: Ordering) -> i16Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: i16, order: Ordering) -> i16Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: i16, order: Ordering) -> i16Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: i16, order: Ordering) -> i16Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<i16, i16> where F: FnMut(i16) -> Option<i16>,An alias for
AtomicI16::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i16) -> Option<i16>) -> Result<i16, i16>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI16::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i16) -> i16) -> i16Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI16::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: i16, order: Ordering) -> i16Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: i16, order: Ordering) -> i16Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i16.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut i16Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut i16instead of&AtomicI16.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicI16; extern "C" { fn my_atomic_op(arg: *mut i16); } let atomic = AtomicI16::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<i32>
const fn new(v: i32) -> SelfCreates a new atomic integer.
Examples
use AtomicI32; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut i32) -> &'a AtomicI32Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut i32 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicI32>()(note that on some platforms this can be bigger thanalign_of::<i32>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut i32) -> *const AtomicI32Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut i32Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut i32) -> &mut SelfGet atomic access to a
&mut i32.Note: This function is only available on targets where
AtomicI32has the same alignment asi32.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [i32]Get non-atomic access to a
&mut [AtomicI32]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicI32, Ordering}; let mut some_ints = [const { AtomicI32::new(0) }; 10]; let view: &mut [i32] = AtomicI32::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [i32]) -> &mut [Self]Get atomic access to a
&mut [i32]slice.Note: This function is only available on targets where
AtomicI32has the same alignment asi32.Examples
use std::sync::atomic::{AtomicI32, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicI32::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> i32Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicI32; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> i32Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> i32Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI32>()(note that on some platforms this can be bigger thanalign_of::<i32>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: i32, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: i32, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI32>()(note that on some platforms this can be bigger thanalign_of::<i32>()).
Panics
-
const fn swap(&self, val: i32, order: Ordering) -> i32Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: i32, new: i32, order: Ordering) -> i32Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: i32, new: i32, success: Ordering, failure: Ordering) -> Result<i32, i32>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: i32, new: i32, success: Ordering, failure: Ordering) -> Result<i32, i32>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicI32::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: i32, order: Ordering) -> i32Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: i32, order: Ordering) -> i32Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: i32, order: Ordering) -> i32Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: i32, order: Ordering) -> i32Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: i32, order: Ordering) -> i32Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: i32, order: Ordering) -> i32Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<i32, i32> where F: FnMut(i32) -> Option<i32>,An alias for
AtomicI32::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i32) -> Option<i32>) -> Result<i32, i32>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI32::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i32) -> i32) -> i32Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI32::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: i32, order: Ordering) -> i32Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: i32, order: Ordering) -> i32Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i32.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut i32Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut i32instead of&AtomicI32.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicI32; extern "C" { fn my_atomic_op(arg: *mut i32); } let atomic = AtomicI32::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<i64>
const fn new(v: i64) -> SelfCreates a new atomic integer.
Examples
use AtomicI64; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut i64) -> &'a AtomicI64Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut i64 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicI64>()(note that on some platforms this can be bigger thanalign_of::<i64>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut i64) -> *const AtomicI64Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut i64Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut i64) -> &mut SelfGet atomic access to a
&mut i64.Note: This function is only available on targets where
AtomicI64has the same alignment asi64.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [i64]Get non-atomic access to a
&mut [AtomicI64]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicI64, Ordering}; let mut some_ints = [const { AtomicI64::new(0) }; 10]; let view: &mut [i64] = AtomicI64::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [i64]) -> &mut [Self]Get atomic access to a
&mut [i64]slice.Note: This function is only available on targets where
AtomicI64has the same alignment asi64.Examples
use std::sync::atomic::{AtomicI64, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicI64::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> i64Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicI64; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> i64Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> i64Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI64>()(note that on some platforms this can be bigger thanalign_of::<i64>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: i64, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: i64, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI64>()(note that on some platforms this can be bigger thanalign_of::<i64>()).
Panics
-
const fn swap(&self, val: i64, order: Ordering) -> i64Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: i64, new: i64, order: Ordering) -> i64Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: i64, new: i64, success: Ordering, failure: Ordering) -> Result<i64, i64>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: i64, new: i64, success: Ordering, failure: Ordering) -> Result<i64, i64>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicI64::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: i64, order: Ordering) -> i64Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: i64, order: Ordering) -> i64Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: i64, order: Ordering) -> i64Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: i64, order: Ordering) -> i64Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: i64, order: Ordering) -> i64Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: i64, order: Ordering) -> i64Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<i64, i64> where F: FnMut(i64) -> Option<i64>,An alias for
AtomicI64::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i64) -> Option<i64>) -> Result<i64, i64>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI64::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i64) -> i64) -> i64Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI64::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: i64, order: Ordering) -> i64Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: i64, order: Ordering) -> i64Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i64.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut i64Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut i64instead of&AtomicI64.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicI64; extern "C" { fn my_atomic_op(arg: *mut i64); } let atomic = AtomicI64::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<i8>
const fn new(v: i8) -> SelfCreates a new atomic integer.
Examples
use AtomicI8; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut i8) -> &'a AtomicI8Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut i8 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicI8>()(note that this is always true, sincealign_of::<AtomicI8>() == 1).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut i8) -> *const AtomicI8Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut i8Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut i8) -> &mut SelfGet atomic access to a
&mut i8.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [i8]Get non-atomic access to a
&mut [AtomicI8]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicI8, Ordering}; let mut some_ints = [const { AtomicI8::new(0) }; 10]; let view: &mut [i8] = AtomicI8::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [i8]) -> &mut [Self]Get atomic access to a
&mut [i8]slice.Examples
use std::sync::atomic::{AtomicI8, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicI8::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> i8Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicI8; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> i8Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> i8Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI8>()(note that this is always true, sincealign_of::<AtomicI8>() == 1). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: i8, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: i8, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicI8>()(note that this is always true, sincealign_of::<AtomicI8>() == 1).
Panics
-
const fn swap(&self, val: i8, order: Ordering) -> i8Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: i8, new: i8, order: Ordering) -> i8Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: i8, new: i8, success: Ordering, failure: Ordering) -> Result<i8, i8>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: i8, new: i8, success: Ordering, failure: Ordering) -> Result<i8, i8>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicI8::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: i8, order: Ordering) -> i8Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: i8, order: Ordering) -> i8Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: i8, order: Ordering) -> i8Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: i8, order: Ordering) -> i8Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: i8, order: Ordering) -> i8Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: i8, order: Ordering) -> i8Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<i8, i8> where F: FnMut(i8) -> Option<i8>,An alias for
AtomicI8::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i8) -> Option<i8>) -> Result<i8, i8>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI8::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i8) -> i8) -> i8Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicI8::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: i8, order: Ordering) -> i8Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: i8, order: Ordering) -> i8Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
i8.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut i8Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut i8instead of&AtomicI8.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicI8; extern "C" { fn my_atomic_op(arg: *mut i8); } let atomic = AtomicI8::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<isize>
const fn new(v: isize) -> SelfCreates a new atomic integer.
Examples
use AtomicIsize; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut isize) -> &'a AtomicIsizeCreates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut isize = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicIsize>()(note that on some platforms this can be bigger thanalign_of::<isize>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut isize) -> *const AtomicIsizeCreates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut isizeReturns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut isize) -> &mut SelfGet atomic access to a
&mut isize.Note: This function is only available on targets where
AtomicIsizehas the same alignment asisize.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [isize]Get non-atomic access to a
&mut [AtomicIsize]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicIsize, Ordering}; let mut some_ints = [const { AtomicIsize::new(0) }; 10]; let view: &mut [isize] = AtomicIsize::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [isize]) -> &mut [Self]Get atomic access to a
&mut [isize]slice.Note: This function is only available on targets where
AtomicIsizehas the same alignment asisize.Examples
use std::sync::atomic::{AtomicIsize, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicIsize::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> isizeConsumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicIsize; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> isizeLoads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> isizePerform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicIsize>()(note that on some platforms this can be bigger thanalign_of::<isize>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: isize, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: isize, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicIsize>()(note that on some platforms this can be bigger thanalign_of::<isize>()).
Panics
-
const fn swap(&self, val: isize, order: Ordering) -> isizeStores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: isize, new: isize, order: Ordering) -> isizeStores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: isize, new: isize, success: Ordering, failure: Ordering) -> Result<isize, isize>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: isize, new: isize, success: Ordering, failure: Ordering) -> Result<isize, isize>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicIsize::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: isize, order: Ordering) -> isizeAdds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: isize, order: Ordering) -> isizeSubtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: isize, order: Ordering) -> isizeBitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: isize, order: Ordering) -> isizeBitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: isize, order: Ordering) -> isizeBitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: isize, order: Ordering) -> isizeBitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<isize, isize> where F: FnMut(isize) -> Option<isize>,An alias for
AtomicIsize::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(isize) -> Option<isize>) -> Result<isize, isize>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicIsize::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(isize) -> isize) -> isizeFetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicIsize::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: isize, order: Ordering) -> isizeMaximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: isize, order: Ordering) -> isizeMinimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
isize.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut isizeReturns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut isizeinstead of&AtomicIsize.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicIsize; extern "C" { fn my_atomic_op(arg: *mut isize); } let atomic = AtomicIsize::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<u128>
const fn new(v: u128) -> SelfCreates a new atomic integer.
Examples
#![feature(integer_atomics)] use std::sync::atomic::AtomicU128; let atomic_forty_two = AtomicU128::new(42);const unsafe fn from_ptr<'a>(ptr: *mut u128) -> &'a AtomicU128Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut u128 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicU128>()(note that on some platforms this can be bigger thanalign_of::<u128>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut u128) -> *const AtomicU128Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut u128Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let mut some_var = AtomicU128::new(10); assert_eq!(*some_var.get_mut(), 10); *some_var.get_mut() = 5; assert_eq!(some_var.load(Ordering::SeqCst), 5);const fn from_mut(v: &mut u128) -> &mut SelfGet atomic access to a
&mut u128.Note: This function is only available on targets where
AtomicU128has the same alignment asu128.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [u128]Get non-atomic access to a
&mut [AtomicU128]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let mut some_ints = [const { AtomicU128::new(0) }; 10]; let view: &mut [u128] = AtomicU128::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [u128]) -> &mut [Self]Get atomic access to a
&mut [u128]slice.Note: This function is only available on targets where
AtomicU128has the same alignment asu128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicU128::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> u128Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
#![feature(integer_atomics)] use std::sync::atomic::AtomicU128; let some_var = AtomicU128::new(5); assert_eq!(some_var.into_inner(), 5);const fn load(&self, order: Ordering) -> u128Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let some_var = AtomicU128::new(5); assert_eq!(some_var.load(Ordering::Relaxed), 5);const unsafe fn load_volatile(self: *const Self, order: Ordering) -> u128Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU128>()(note that on some platforms this can be bigger thanalign_of::<u128>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: u128, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let some_var = AtomicU128::new(5); some_var.store(10, Ordering::Relaxed); assert_eq!(some_var.load(Ordering::Relaxed), 10);const unsafe fn store_volatile(self: *const Self, val: u128, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU128>()(note that on some platforms this can be bigger thanalign_of::<u128>()).
Panics
-
const fn swap(&self, val: u128, order: Ordering) -> u128Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let some_var = AtomicU128::new(5); assert_eq!(some_var.swap(10, Ordering::Relaxed), 5);const fn compare_and_swap(&self, current: u128, new: u128, order: Ordering) -> u128Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let some_var = AtomicU128::new(5); assert_eq!(some_var.compare_and_swap(5, 10, Ordering::Relaxed), 5); assert_eq!(some_var.load(Ordering::Relaxed), 10); assert_eq!(some_var.compare_and_swap(6, 12, Ordering::Relaxed), 10); assert_eq!(some_var.load(Ordering::Relaxed), 10);const fn compare_exchange(&self, current: u128, new: u128, success: Ordering, failure: Ordering) -> Result<u128, u128>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let some_var = AtomicU128::new(5); assert_eq!(some_var.compare_exchange(5, 10, Ordering::Acquire, Ordering::Relaxed), Ok(5)); assert_eq!(some_var.load(Ordering::Relaxed), 10); assert_eq!(some_var.compare_exchange(6, 12, Ordering::SeqCst, Ordering::Acquire), Err(10)); assert_eq!(some_var.load(Ordering::Relaxed), 10);Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: u128, new: u128, success: Ordering, failure: Ordering) -> Result<u128, u128>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicU128::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let val = AtomicU128::new(4); let mut old = val.load(Ordering::Relaxed); loop { let new = old * 2; match val.compare_exchange_weak(old, new, Ordering::SeqCst, Ordering::Relaxed) { Ok(_) => break, Err(x) => old = x, } }Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: u128, order: Ordering) -> u128Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(0); assert_eq!(foo.fetch_add(10, Ordering::SeqCst), 0); assert_eq!(foo.load(Ordering::SeqCst), 10);const fn fetch_sub(&self, val: u128, order: Ordering) -> u128Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(20); assert_eq!(foo.fetch_sub(10, Ordering::SeqCst), 20); assert_eq!(foo.load(Ordering::SeqCst), 10);const fn fetch_and(&self, val: u128, order: Ordering) -> u128Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(0b101101); assert_eq!(foo.fetch_and(0b110011, Ordering::SeqCst), 0b101101); assert_eq!(foo.load(Ordering::SeqCst), 0b100001);const fn fetch_nand(&self, val: u128, order: Ordering) -> u128Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(0x13); assert_eq!(foo.fetch_nand(0x31, Ordering::SeqCst), 0x13); assert_eq!(foo.load(Ordering::SeqCst), !(0x13 & 0x31));const fn fetch_or(&self, val: u128, order: Ordering) -> u128Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(0b101101); assert_eq!(foo.fetch_or(0b110011, Ordering::SeqCst), 0b101101); assert_eq!(foo.load(Ordering::SeqCst), 0b111111);const fn fetch_xor(&self, val: u128, order: Ordering) -> u128Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(0b101101); assert_eq!(foo.fetch_xor(0b110011, Ordering::SeqCst), 0b101101); assert_eq!(foo.load(Ordering::SeqCst), 0b011110);fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<u128, u128> where F: FnMut(u128) -> Option<u128>,An alias for
AtomicU128::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u128) -> Option<u128>) -> Result<u128, u128>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU128::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u128) -> u128) -> u128Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU128::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: u128, order: Ordering) -> u128Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(23); assert_eq!(foo.fetch_max(42, Ordering::SeqCst), 23); assert_eq!(foo.load(Ordering::SeqCst), 42);If you want to obtain the maximum value in one step, you can use the following:
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(23); let bar = 42; let max_foo = foo.fetch_max(bar, Ordering::SeqCst).max(bar); assert!(max_foo == 42);const fn fetch_min(&self, val: u128, order: Ordering) -> u128Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u128.Examples
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(23); assert_eq!(foo.fetch_min(42, Ordering::Relaxed), 23); assert_eq!(foo.load(Ordering::Relaxed), 23); assert_eq!(foo.fetch_min(22, Ordering::Relaxed), 23); assert_eq!(foo.load(Ordering::Relaxed), 22);If you want to obtain the minimum value in one step, you can use the following:
#![feature(integer_atomics)] use std::sync::atomic::{AtomicU128, Ordering}; let foo = AtomicU128::new(23); let bar = 12; let min_foo = foo.fetch_min(bar, Ordering::SeqCst).min(bar); assert_eq!(min_foo, 12);const fn as_ptr(&self) -> *mut u128Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut u128instead of&AtomicU128.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { #![feature(integer_atomics)] use std::sync::atomic::AtomicU128; extern "C" { fn my_atomic_op(arg: *mut u128); } let atomic = AtomicU128::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<u16>
const fn new(v: u16) -> SelfCreates a new atomic integer.
Examples
use AtomicU16; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut u16) -> &'a AtomicU16Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut u16 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicU16>()(note that on some platforms this can be bigger thanalign_of::<u16>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut u16) -> *const AtomicU16Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut u16Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut u16) -> &mut SelfGet atomic access to a
&mut u16.Note: This function is only available on targets where
AtomicU16has the same alignment asu16.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [u16]Get non-atomic access to a
&mut [AtomicU16]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicU16, Ordering}; let mut some_ints = [const { AtomicU16::new(0) }; 10]; let view: &mut [u16] = AtomicU16::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [u16]) -> &mut [Self]Get atomic access to a
&mut [u16]slice.Note: This function is only available on targets where
AtomicU16has the same alignment asu16.Examples
use std::sync::atomic::{AtomicU16, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicU16::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> u16Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicU16; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> u16Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> u16Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU16>()(note that on some platforms this can be bigger thanalign_of::<u16>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: u16, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: u16, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU16>()(note that on some platforms this can be bigger thanalign_of::<u16>()).
Panics
-
const fn swap(&self, val: u16, order: Ordering) -> u16Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: u16, new: u16, order: Ordering) -> u16Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: u16, new: u16, success: Ordering, failure: Ordering) -> Result<u16, u16>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: u16, new: u16, success: Ordering, failure: Ordering) -> Result<u16, u16>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicU16::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: u16, order: Ordering) -> u16Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: u16, order: Ordering) -> u16Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: u16, order: Ordering) -> u16Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: u16, order: Ordering) -> u16Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: u16, order: Ordering) -> u16Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: u16, order: Ordering) -> u16Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<u16, u16> where F: FnMut(u16) -> Option<u16>,An alias for
AtomicU16::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u16) -> Option<u16>) -> Result<u16, u16>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU16::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u16) -> u16) -> u16Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU16::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: u16, order: Ordering) -> u16Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: u16, order: Ordering) -> u16Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u16.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut u16Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut u16instead of&AtomicU16.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicU16; extern "C" { fn my_atomic_op(arg: *mut u16); } let atomic = AtomicU16::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<u32>
const fn new(v: u32) -> SelfCreates a new atomic integer.
Examples
use AtomicU32; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut u32) -> &'a AtomicU32Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut u32 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicU32>()(note that on some platforms this can be bigger thanalign_of::<u32>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut u32) -> *const AtomicU32Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut u32Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut u32) -> &mut SelfGet atomic access to a
&mut u32.Note: This function is only available on targets where
AtomicU32has the same alignment asu32.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [u32]Get non-atomic access to a
&mut [AtomicU32]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicU32, Ordering}; let mut some_ints = [const { AtomicU32::new(0) }; 10]; let view: &mut [u32] = AtomicU32::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [u32]) -> &mut [Self]Get atomic access to a
&mut [u32]slice.Note: This function is only available on targets where
AtomicU32has the same alignment asu32.Examples
use std::sync::atomic::{AtomicU32, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicU32::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> u32Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicU32; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> u32Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> u32Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU32>()(note that on some platforms this can be bigger thanalign_of::<u32>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: u32, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: u32, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU32>()(note that on some platforms this can be bigger thanalign_of::<u32>()).
Panics
-
const fn swap(&self, val: u32, order: Ordering) -> u32Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: u32, new: u32, order: Ordering) -> u32Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: u32, new: u32, success: Ordering, failure: Ordering) -> Result<u32, u32>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: u32, new: u32, success: Ordering, failure: Ordering) -> Result<u32, u32>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicU32::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: u32, order: Ordering) -> u32Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: u32, order: Ordering) -> u32Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: u32, order: Ordering) -> u32Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: u32, order: Ordering) -> u32Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: u32, order: Ordering) -> u32Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: u32, order: Ordering) -> u32Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<u32, u32> where F: FnMut(u32) -> Option<u32>,An alias for
AtomicU32::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u32) -> Option<u32>) -> Result<u32, u32>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU32::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u32) -> u32) -> u32Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU32::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: u32, order: Ordering) -> u32Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: u32, order: Ordering) -> u32Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u32.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut u32Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut u32instead of&AtomicU32.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicU32; extern "C" { fn my_atomic_op(arg: *mut u32); } let atomic = AtomicU32::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<u64>
const fn new(v: u64) -> SelfCreates a new atomic integer.
Examples
use AtomicU64; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut u64) -> &'a AtomicU64Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut u64 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicU64>()(note that on some platforms this can be bigger thanalign_of::<u64>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut u64) -> *const AtomicU64Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut u64Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut u64) -> &mut SelfGet atomic access to a
&mut u64.Note: This function is only available on targets where
AtomicU64has the same alignment asu64.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [u64]Get non-atomic access to a
&mut [AtomicU64]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicU64, Ordering}; let mut some_ints = [const { AtomicU64::new(0) }; 10]; let view: &mut [u64] = AtomicU64::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [u64]) -> &mut [Self]Get atomic access to a
&mut [u64]slice.Note: This function is only available on targets where
AtomicU64has the same alignment asu64.Examples
use std::sync::atomic::{AtomicU64, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicU64::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> u64Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicU64; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> u64Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> u64Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU64>()(note that on some platforms this can be bigger thanalign_of::<u64>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: u64, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: u64, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU64>()(note that on some platforms this can be bigger thanalign_of::<u64>()).
Panics
-
const fn swap(&self, val: u64, order: Ordering) -> u64Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: u64, new: u64, order: Ordering) -> u64Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: u64, new: u64, success: Ordering, failure: Ordering) -> Result<u64, u64>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: u64, new: u64, success: Ordering, failure: Ordering) -> Result<u64, u64>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicU64::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: u64, order: Ordering) -> u64Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: u64, order: Ordering) -> u64Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: u64, order: Ordering) -> u64Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: u64, order: Ordering) -> u64Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: u64, order: Ordering) -> u64Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: u64, order: Ordering) -> u64Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<u64, u64> where F: FnMut(u64) -> Option<u64>,An alias for
AtomicU64::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u64) -> Option<u64>) -> Result<u64, u64>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU64::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u64) -> u64) -> u64Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU64::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: u64, order: Ordering) -> u64Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: u64, order: Ordering) -> u64Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u64.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut u64Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut u64instead of&AtomicU64.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicU64; extern "C" { fn my_atomic_op(arg: *mut u64); } let atomic = AtomicU64::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<u8>
const fn new(v: u8) -> SelfCreates a new atomic integer.
Examples
use AtomicU8; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut u8) -> &'a AtomicU8Creates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut u8 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicU8>()(note that this is always true, sincealign_of::<AtomicU8>() == 1).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut u8) -> *const AtomicU8Creates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut u8Returns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut u8) -> &mut SelfGet atomic access to a
&mut u8.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [u8]Get non-atomic access to a
&mut [AtomicU8]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicU8, Ordering}; let mut some_ints = [const { AtomicU8::new(0) }; 10]; let view: &mut [u8] = AtomicU8::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [u8]) -> &mut [Self]Get atomic access to a
&mut [u8]slice.Examples
use std::sync::atomic::{AtomicU8, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicU8::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> u8Consumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicU8; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> u8Loads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> u8Perform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU8>()(note that this is always true, sincealign_of::<AtomicU8>() == 1). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: u8, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: u8, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicU8>()(note that this is always true, sincealign_of::<AtomicU8>() == 1).
Panics
-
const fn swap(&self, val: u8, order: Ordering) -> u8Stores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: u8, new: u8, order: Ordering) -> u8Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: u8, new: u8, success: Ordering, failure: Ordering) -> Result<u8, u8>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: u8, new: u8, success: Ordering, failure: Ordering) -> Result<u8, u8>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicU8::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: u8, order: Ordering) -> u8Adds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: u8, order: Ordering) -> u8Subtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: u8, order: Ordering) -> u8Bitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: u8, order: Ordering) -> u8Bitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: u8, order: Ordering) -> u8Bitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: u8, order: Ordering) -> u8Bitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<u8, u8> where F: FnMut(u8) -> Option<u8>,An alias for
AtomicU8::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u8) -> Option<u8>) -> Result<u8, u8>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU8::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u8) -> u8) -> u8Fetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicU8::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: u8, order: Ordering) -> u8Maximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: u8, order: Ordering) -> u8Minimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
u8.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut u8Returns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut u8instead of&AtomicU8.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicU8; extern "C" { fn my_atomic_op(arg: *mut u8); } let atomic = AtomicU8::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl Atomic<usize>
const fn new(v: usize) -> SelfCreates a new atomic integer.
Examples
use AtomicUsize; let atomic_forty_two = new;const unsafe fn from_ptr<'a>(ptr: *mut usize) -> &'a AtomicUsizeCreates a new reference to an atomic integer from a pointer.
Examples
use ; // Get a pointer to an allocated value let ptr: *mut usize = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert_eq!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicUsize>()(note that on some platforms this can be bigger thanalign_of::<usize>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut usize) -> *const AtomicUsizeCreates a new pointer to an atomic integer from a pointer.
This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn get_mut(&mut self) -> &mut usizeReturns a mutable reference to the underlying integer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut some_var = new; assert_eq!; *some_var.get_mut = 5; assert_eq!;const fn from_mut(v: &mut usize) -> &mut SelfGet atomic access to a
&mut usize.Note: This function is only available on targets where
AtomicUsizehas the same alignment asusize.Examples
use ; let mut some_int = 123; let a = from_mut; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [usize]Get non-atomic access to a
&mut [AtomicUsize]sliceThis is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::sync::atomic::{AtomicUsize, Ordering}; let mut some_ints = [const { AtomicUsize::new(0) }; 10]; let view: &mut [usize] = AtomicUsize::get_mut_slice(&mut some_ints); assert_eq!(view, [0; 10]); view .iter_mut() .enumerate() .for_each(|(idx, int)| *int = idx as _); std::thread::scope(|s| { some_ints .iter() .enumerate() .for_each(|(idx, int)| { s.spawn(move || assert_eq!(int.load(Ordering::Relaxed), idx as _)); }) });const fn from_mut_slice(v: &mut [usize]) -> &mut [Self]Get atomic access to a
&mut [usize]slice.Note: This function is only available on targets where
AtomicUsizehas the same alignment asusize.Examples
use std::sync::atomic::{AtomicUsize, Ordering}; let mut some_ints = [0; 10]; let a = &*AtomicUsize::from_mut_slice(&mut some_ints); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || a[i].store(i as _, Ordering::Relaxed)); } }); for (i, n) in some_ints.into_iter().enumerate() { assert_eq!(i, n as usize); }const fn into_inner(self) -> usizeConsumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicUsize; let some_var = new; assert_eq!;const fn load(&self, order: Ordering) -> usizeLoads a value from the atomic integer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let some_var = new; assert_eq!;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> usizePerform a volatile load from the atomic integer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicUsize>()(note that on some platforms this can be bigger thanalign_of::<usize>()). -
Reading from
selfmust produce a properly initialized value of the underlying integer type.
Panics
-
const fn store(&self, val: usize, order: Ordering)Stores a value into the atomic integer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let some_var = new; some_var.store; assert_eq!;const unsafe fn store_volatile(self: *const Self, val: usize, order: Ordering)Performs a volatile store into the atomic integer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicUsize>()(note that on some platforms this can be bigger thanalign_of::<usize>()).
Panics
-
const fn swap(&self, val: usize, order: Ordering) -> usizeStores a value into the atomic integer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let some_var = new; assert_eq!;const fn compare_and_swap(&self, current: usize, new: usize, order: Ordering) -> usizeStores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn compare_exchange(&self, current: usize, new: usize, success: Ordering, failure: Ordering) -> Result<usize, usize>Stores a value into the atomic integer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let some_var = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim! This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn compare_exchange_weak(&self, current: usize, new: usize, success: Ordering, failure: Ordering) -> Result<usize, usize>Stores a value into the atomic integer if the current value is the same as the
currentvalue.Unlike
AtomicUsize::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let val = new; let mut old = val.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.const fn fetch_add(&self, val: usize, order: Ordering) -> usizeAdds to the current value, returning the previous value.
This operation wraps around on overflow.
fetch_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_sub(&self, val: usize, order: Ordering) -> usizeSubtracts from the current value, returning the previous value.
This operation wraps around on overflow.
fetch_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_and(&self, val: usize, order: Ordering) -> usizeBitwise "and" with the current value.
Performs a bitwise "and" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_nand(&self, val: usize, order: Ordering) -> usizeBitwise "nand" with the current value.
Performs a bitwise "nand" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_nandtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_or(&self, val: usize, order: Ordering) -> usizeBitwise "or" with the current value.
Performs a bitwise "or" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let foo = new; assert_eq!; assert_eq!;const fn fetch_xor(&self, val: usize, order: Ordering) -> usizeBitwise "xor" with the current value.
Performs a bitwise "xor" operation on the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let foo = new; assert_eq!; assert_eq!;fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<usize, usize> where F: FnMut(usize) -> Option<usize>,An alias for
AtomicUsize::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(usize) -> Option<usize>) -> Result<usize, usize>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicUsize::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(usize) -> usize) -> usizeFetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicUsize::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem if this atomic integer is an index or more generally if knowledge of only the bitwise value of the atomic is not in and of itself sufficient to ensure any required preconditions.
Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!;const fn fetch_max(&self, val: usize, order: Ordering) -> usizeMaximum with the current value.
Finds the maximum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_maxtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let foo = new; assert_eq!; assert_eq!;If you want to obtain the maximum value in one step, you can use the following:
use ; let foo = new; let bar = 42; let max_foo = foo.fetch_max.max; assert!;const fn fetch_min(&self, val: usize, order: Ordering) -> usizeMinimum with the current value.
Finds the minimum of the current value and the argument
val, and sets the new value to the result.Returns the previous value.
fetch_mintakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
usize.Examples
use ; let foo = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;If you want to obtain the minimum value in one step, you can use the following:
use ; let foo = new; let bar = 12; let min_foo = foo.fetch_min.min; assert_eq!;const fn as_ptr(&self) -> *mut usizeReturns a mutable pointer to the underlying integer.
Doing non-atomic reads and writes on the resulting integer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut usizeinstead of&AtomicUsize.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
# fn main() { use std::sync::atomic::AtomicUsize; extern "C" { fn my_atomic_op(arg: *mut usize); } let atomic = AtomicUsize::new(1); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); } # }
impl<T> Atomic<*mut T>
const fn new(p: *mut T) -> AtomicPtr<T>Creates a new
AtomicPtr.Examples
use AtomicPtr; let ptr = &mut 5; let atomic_ptr = new;const unsafe fn from_ptr<'a>(ptr: *mut *mut T) -> &'a AtomicPtr<T>Creates a new
AtomicPtrfrom a pointer.Examples
use ; // Get a pointer to an allocated value let ptr: *mut *mut u8 = Boxinto_raw; assert!; // It's ok to non-atomically access the value behind `ptr`, // since the reference to the atomic ended its lifetime in the block above assert!; // Deallocate the value unsafeSafety
ptrmust be aligned toalign_of::<AtomicPtr<T>>()(note that on some platforms this can be bigger thanalign_of::<*mut T>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- You must adhere to the Memory model for atomic accesses. In particular, it is not allowed to mix conflicting atomic and non-atomic accesses, or atomic accesses of different sizes, without synchronization.
const fn from_ptr_raw(ptr: *mut *mut T) -> *const AtomicPtr<T>Creates a new pointer to
AtomicPtrfrom a pointer.This is useful if you want to do volatile atomic accesses, and thus avoid creating a reference to the destination.
const fn null() -> AtomicPtr<T>Creates a new
AtomicPtrinitialized with a null pointer.Examples
use ; let atomic_ptr = null; assert!;const fn get_mut(&mut self) -> &mut *mut TReturns a mutable reference to the underlying pointer.
This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use ; let mut data = 10; let mut atomic_ptr = new; let mut other_data = 5; *atomic_ptr.get_mut = &mut other_data; assert_eq!;const fn from_mut(v: &mut *mut T) -> &mut SelfGets atomic access to a pointer.
Note: This function is only available on targets where
AtomicPtr<T>has the same alignment as*const TExamples
use ; let mut data = 123; let mut some_ptr = &mut data as *mut i32; let a = from_mut; let mut other_data = 456; a.store; assert_eq!;const fn get_mut_slice(this: &mut [Self]) -> &mut [*mut T]Gets non-atomic access to a
&mut [AtomicPtr]slice.This is safe because the mutable reference guarantees that no other threads are concurrently accessing the atomic data.
Examples
use std::ptr::null_mut; use std::sync::atomic::{AtomicPtr, Ordering}; let mut some_ptrs = [const { AtomicPtr::new(null_mut::<String>()) }; 10]; let view: &mut [*mut String] = AtomicPtr::get_mut_slice(&mut some_ptrs); assert_eq!(view, [null_mut::<String>(); 10]); view .iter_mut() .enumerate() .for_each(|(i, ptr)| *ptr = Box::into_raw(Box::new(format!("iteration#{i}")))); std::thread::scope(|s| { for ptr in &some_ptrs { s.spawn(move || { let ptr = ptr.load(Ordering::Relaxed); assert!(!ptr.is_null()); let name = unsafe { Box::from_raw(ptr) }; println!("Hello, {name}!"); }); } });const fn from_mut_slice(v: &mut [*mut T]) -> &mut [Self]Gets atomic access to a slice of pointers.
Note: This function is only available on targets where
AtomicPtr<T>has the same alignment as*const TExamples
use std::ptr::null_mut; use std::sync::atomic::{AtomicPtr, Ordering}; let mut some_ptrs = [null_mut::<String>(); 10]; let a = &*AtomicPtr::from_mut_slice(&mut some_ptrs); std::thread::scope(|s| { for i in 0..a.len() { s.spawn(move || { let name = Box::new(format!("thread{i}")); a[i].store(Box::into_raw(name), Ordering::Relaxed); }); } }); for p in some_ptrs { assert!(!p.is_null()); let name = unsafe { Box::from_raw(p) }; println!("Hello, {name}!"); }const fn into_inner(self) -> *mut TConsumes the atomic and returns the contained value.
This is safe because passing
selfby value guarantees that no other threads are concurrently accessing the atomic data.Examples
use AtomicPtr; let mut data = 5; let atomic_ptr = new; assert_eq!;const fn load(&self, order: Ordering) -> *mut TLoads a value from the pointer.
loadtakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Panics
Panics if
orderisReleaseorAcqRel.Examples
use ; let ptr = &mut 5; let some_ptr = new; let value = some_ptr.load;const unsafe fn load_volatile(self: *const Self, order: Ordering) -> *mut TPerform a volatile atomic load from the pointer.
load_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,AcquireandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls, but less opaque), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
load][Self::load], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to reusing data from a previous load. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for reads. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a read are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance][crate::ptr::without_provenance]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic load. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be valid for reads, orselfmust point to memory outside of all Rust allocations and reading from that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicPtr<T>>()(note that on some platforms this can be bigger thanalign_of::<*mut T>()). -
Reading from
selfmust produce a properly initialized value of type*mut T.
Panics
Panics if
orderisReleaseorAcqRel.Examples
Assuming an MMIO region at
MMIO_ADDRthat belongs to a device with direct memory access, we may receive a buffer in shared memory from that device as follows:use ; use ptr; const MMIO_ADDR: *mut *mut u8 = without_provenance_mut; let atomic_ptr = from_ptr_raw; // Spin until we see a non-zero value. let buf = 'buf: loop ; // Synchronize with the store whose value we just read. // Note: a standard acquire fence may not be sufficient to synchronize with DMA devices. // Depending on your target, you may have to use inline assembly to emit a special fence. fence; // Now process the data in `buf`.-
const fn store(&self, ptr: *mut T, order: Ordering)Stores a value into the pointer.
storetakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Panics
Panics if
orderisAcquireorAcqRel.Examples
use ; let ptr = &mut 5; let some_ptr = new; let other_ptr = &mut 10; some_ptr.store;const unsafe fn store_volatile(self: *const Self, ptr: *mut T, order: Ordering)Performs a volatile atomic store into the pointer.
store_volatiletakes anOrderingargument which describes the memory ordering of this operation. Possible values areSeqCst,ReleaseandRelaxed.Volatile operations are intended to act on I/O memory. As such, they are considered externally observable events (just like syscalls), and are guaranteed to not be elided or reordered by the compiler across other externally observable events. With this in mind, there are two cases of usage that need to be distinguished:
-
When a volatile operation is used for memory inside an allocation, it behaves exactly like [
store][Self::store], except for the additional guarantee that it won't be elided or reordered across other externally observable events (see above). This implies that the operation will actually access memory and not e.g. be lowered to a register access. Other than that, all the usual rules for memory accesses apply (including provenance). -
Volatile operations, however, may also be used to access memory that is outside of any Rust allocation. In this use-case, the pointer does not have to be valid for writes. This is typically used for CPU and peripheral registers that must be accessed via an I/O memory mapping, most commonly at fixed addresses reserved by the hardware. These often have special semantics associated to their manipulation, and cannot be used as general purpose memory. Here, any address value is possible, including 0 and
usize::MAX, so long as the semantics of such a write are well-defined by the target hardware. The provenance of the pointer is irrelevant, and it can be created with [without_provenance_mut][crate::ptr::without_provenance_mut]. The access is allowed to trap, which must immediately abort the process. It can also cause other side-effects, but those must not affect Rust-allocated memory in any way.
In both cases, the access is also considered atomic with the given
order. This allows synchronization with other threads or devices that share memory with this program.When invoked during const evaluation, this behaves like a regular atomic store. In particular, such reads must always follow the first of the two cases above.
Safety
Behavior is undefined if any of the following conditions are violated:
-
selfmust be either valid for writes, orselfmust point to memory outside of all Rust allocations and writing to that memory must:- not trap, and
- not cause any memory inside a Rust allocation to be modified.
-
selfmust be aligned toalign_of::<AtomicPtr<T>>()(note that on some platforms this can be bigger thanalign_of::<*mut T>()).
Panics
Panics if
orderisAcquireorAcqRel.Examples
Assuming an MMIO region at
MMIO_ADDRthat belongs to a device with direct memory access, we may submit a buffer in shared memory to that device as follows:use ; use ptr; const MMIO_ADDR: *mut *mut u8 = without_provenance_mut; let atomic_ptr = from_ptr_raw; // Prepare some data for the DMA device. # *mut u8 let buf = get_dma_buffer; // Ensure the other side can synchronize with the store we do below. // Note: a standard release fence may not be sufficient to synchronize with DMA devices. // Depending on your target, you may have to use inline assembly to emit a special fence. fence; unsafe ;-
const fn swap(&self, ptr: *mut T, order: Ordering) -> *mut TStores a value into the pointer, returning the previous value.
swaptakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on pointers.
Examples
use ; let ptr = &mut 5; let some_ptr = new; let other_ptr = &mut 10; let value = some_ptr.swap;fn compare_and_swap(&self, current: *mut T, new: *mut T, order: Ordering) -> *mut TStores a value into the pointer if the current value is the same as the
currentvalue.The return value is always the previous value. If it is equal to
current, then the value was updated.compare_and_swapalso takes anOrderingargument which describes the memory ordering of this operation. Notice that even when usingAcqRel, the operation might fail and hence just perform anAcquireload, but not haveReleasesemantics. UsingAcquiremakes the store part of this operationRelaxedif it happens, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on pointers.
Migrating to
compare_exchangeandcompare_exchange_weakcompare_and_swapis equivalent tocompare_exchangewith the following mapping for memory orderings:Original Success Failure Relaxed Relaxed Relaxed Acquire Acquire Acquire Release Release Relaxed AcqRel AcqRel Acquire SeqCst SeqCst SeqCst compare_and_swapandcompare_exchangealso differ in their return type. You can usecompare_exchange(...).unwrap_or_else(|x| x)to recover the behavior ofcompare_and_swap, but in most cases it is more idiomatic to check whether the return value isOkorErrrather than to infer success vs failure based on the value that was read.During migration, consider whether it makes sense to use
compare_exchange_weakinstead.compare_exchange_weakis allowed to fail spuriously even when the comparison succeeds, which allows the compiler to generate better assembly code when the compare and swap is used in a loop.Examples
use ; let ptr = &mut 5; let some_ptr = new; let other_ptr = &mut 10; let value = some_ptr.compare_and_swap;fn compare_exchange(&self, current: *mut T, new: *mut T, success: Ordering, failure: Ordering) -> Result<*mut T, *mut T>Stores a value into the pointer if the current value is the same as the
currentvalue.The return value is a result indicating whether the new value was written and containing the previous value. On success this value is guaranteed to be equal to
current.compare_exchangetakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on pointers.
Examples
use ; let ptr = &mut 5; let some_ptr = new; let other_ptr = &mut 10; let value = some_ptr.compare_exchange;Considerations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.fn compare_exchange_weak(&self, current: *mut T, new: *mut T, success: Ordering, failure: Ordering) -> Result<*mut T, *mut T>Stores a value into the pointer if the current value is the same as the
currentvalue.Unlike
AtomicPtr::compare_exchange, this function is allowed to spuriously fail even when the comparison succeeds, which can result in more efficient code on some platforms. The return value is a result indicating whether the new value was written and containing the previous value.compare_exchange_weaktakes twoOrderingarguments to describe the memory ordering of this operation.successdescribes the required ordering for the read-modify-write operation that takes place if the comparison withcurrentsucceeds.failuredescribes the required ordering for the load operation that takes place when the comparison fails. UsingAcquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the successful loadRelaxed. The failure ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on pointers.
Examples
use ; let some_ptr = new; let new = &mut 10; let mut old = some_ptr.load; loopConsiderations
compare_exchangeis a compare-and-swap operation and thus exhibits the usual downsides of CAS operations. In particular, a load of the value followed by a successfulcompare_exchangewith the previous load does not ensure that other threads have not changed the value in the interim. This is usually important when the equality check in thecompare_exchangeis being used to check the identity of a value, but equality does not necessarily imply identity. This is a particularly common case for pointers, as a pointer holding the same address does not imply that the same object exists at that address! In this case,compare_exchangecan lead to the ABA problem.fn fetch_update<F>(&self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<*mut T, *mut T> where F: FnMut(*mut T) -> Option<*mut T>,An alias for
AtomicPtr::try_update.fn try_update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(*mut T) -> Option<*mut T>) -> Result<*mut T, *mut T>Fetches the value, and applies a function to it that returns an optional new value. Returns a
ResultofOk(previous_value)if the function returnedSome(_), elseErr(previous_value).See also:
update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, as long as the function returns
Some(_), but the function will have been applied only once to the stored value.try_updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicPtr::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on pointers.
Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem, which is a particularly common pitfall for pointers!
Examples
use ; let ptr: *mut _ = &mut 5; let some_ptr = new; let new: *mut _ = &mut 10; assert_eq!; let result = some_ptr.try_update; assert_eq!; assert_eq!;fn update(&self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(*mut T) -> *mut T) -> *mut TFetches the value, and applies a function to it that returns a new value. The new value is stored and the old value is returned.
See also:
try_update.Note: This may call the function multiple times if the value has been changed from other threads in the meantime, but the function will have been applied only once to the stored value.
updatetakes twoOrderingarguments to describe the memory ordering of this operation. The first describes the required ordering for when the operation finally succeeds while the second describes the required ordering for loads. These correspond to the success and failure orderings ofAtomicPtr::compare_exchangerespectively.Using
Acquireas success ordering makes the store part of this operationRelaxed, and usingReleasemakes the final successful loadRelaxed. The (failed) load ordering can only beSeqCst,AcquireorRelaxed.Note: This method is only available on platforms that support atomic operations on pointers.
Considerations
This method is not magic; it is not provided by the hardware, and does not act like a critical section or mutex.
It is implemented on top of an atomic compare-and-swap operation, and thus is subject to the usual drawbacks of CAS operations. In particular, be careful of the ABA problem, which is a particularly common pitfall for pointers!
Examples
use ; let ptr: *mut _ = &mut 5; let some_ptr = new; let new: *mut _ = &mut 10; let result = some_ptr.update; assert_eq!; assert_eq!;fn fetch_ptr_add(&self, val: usize, order: Ordering) -> *mut TOffsets the pointer's address by adding
val(in units ofT), returning the previous pointer.This is equivalent to using
wrapping_addto atomically perform the equivalent ofptr = ptr.wrapping_add(val);.This method operates in units of
T, which means that it cannot be used to offset the pointer by an amount which is not a multiple ofsize_of::<T>(). This can sometimes be inconvenient, as you may want to work with a deliberately misaligned pointer. In such cases, you may use thefetch_byte_addmethod instead.fetch_ptr_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
AtomicPtr.Examples
use ; let atom = new; assert_eq!; // Note: units of `size_of::<i64>()`. assert_eq!;fn fetch_ptr_sub(&self, val: usize, order: Ordering) -> *mut TOffsets the pointer's address by subtracting
val(in units ofT), returning the previous pointer.This is equivalent to using
wrapping_subto atomically perform the equivalent ofptr = ptr.wrapping_sub(val);.This method operates in units of
T, which means that it cannot be used to offset the pointer by an amount which is not a multiple ofsize_of::<T>(). This can sometimes be inconvenient, as you may want to work with a deliberately misaligned pointer. In such cases, you may use thefetch_byte_submethod instead.fetch_ptr_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
AtomicPtr.Examples
use ; let array = ; let atom = new; assert!; assert!;fn fetch_byte_add(&self, val: usize, order: Ordering) -> *mut TOffsets the pointer's address by adding
valbytes, returning the previous pointer.This is equivalent to using
wrapping_byte_addto atomically performptr = ptr.wrapping_byte_add(val).fetch_byte_addtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
AtomicPtr.Examples
use ; let atom = new; assert_eq!; // Note: in units of bytes, not `size_of::<i64>()`. assert_eq!;fn fetch_byte_sub(&self, val: usize, order: Ordering) -> *mut TOffsets the pointer's address by subtracting
valbytes, returning the previous pointer.This is equivalent to using
wrapping_byte_subto atomically performptr = ptr.wrapping_byte_sub(val).fetch_byte_subtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
AtomicPtr.Examples
use ; let mut arr = ; let atom = new; assert_eq!; assert_eq!;fn fetch_or(&self, val: usize, order: Ordering) -> *mut TPerforms a bitwise "or" operation on the address of the current pointer, and the argument
val, and stores a pointer with provenance of the current pointer and the resulting address.This is equivalent to using
map_addrto atomically performptr = ptr.map_addr(|a| a | val). This can be used in tagged pointer schemes to atomically set tag bits.Caveat: This operation returns the previous value. To compute the stored value without losing provenance, you may use
map_addr. For example:a.fetch_or(val).map_addr(|a| a | val).fetch_ortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
AtomicPtr.This API and its claimed semantics are part of the Strict Provenance experiment, see the [module documentation for
ptr][crate::ptr] for details.Examples
use ; let pointer = &mut 3i64 as *mut i64; let atom = new; // Tag the bottom bit of the pointer. assert_eq!; // Extract and untag. let tagged = atom.load; assert_eq!; assert_eq!;fn fetch_and(&self, val: usize, order: Ordering) -> *mut TPerforms a bitwise "and" operation on the address of the current pointer, and the argument
val, and stores a pointer with provenance of the current pointer and the resulting address.This is equivalent to using
map_addrto atomically performptr = ptr.map_addr(|a| a & val). This can be used in tagged pointer schemes to atomically unset tag bits.Caveat: This operation returns the previous value. To compute the stored value without losing provenance, you may use
map_addr. For example:a.fetch_and(val).map_addr(|a| a & val).fetch_andtakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
AtomicPtr.This API and its claimed semantics are part of the Strict Provenance experiment, see the [module documentation for
ptr][crate::ptr] for details.Examples
use ; let pointer = &mut 3i64 as *mut i64; // A tagged pointer let atom = new; assert_eq!; // Untag, and extract the previously tagged pointer. let untagged = atom.fetch_and .map_addr; assert_eq!;fn fetch_xor(&self, val: usize, order: Ordering) -> *mut TPerforms a bitwise "xor" operation on the address of the current pointer, and the argument
val, and stores a pointer with provenance of the current pointer and the resulting address.This is equivalent to using
map_addrto atomically performptr = ptr.map_addr(|a| a ^ val). This can be used in tagged pointer schemes to atomically toggle tag bits.Caveat: This operation returns the previous value. To compute the stored value without losing provenance, you may use
map_addr. For example:a.fetch_xor(val).map_addr(|a| a ^ val).fetch_xortakes anOrderingargument which describes the memory ordering of this operation. All ordering modes are possible. Note that usingAcquiremakes the store part of this operationRelaxed, and usingReleasemakes the load partRelaxed.Note: This method is only available on platforms that support atomic operations on
AtomicPtr.This API and its claimed semantics are part of the Strict Provenance experiment, see the [module documentation for
ptr][crate::ptr] for details.Examples
use ; let pointer = &mut 3i64 as *mut i64; let atom = new; // Toggle a tag bit on the pointer. atom.fetch_xor; assert_eq!;const fn as_ptr(&self) -> *mut *mut TReturns a mutable pointer to the underlying pointer.
Doing non-atomic reads and writes on the resulting pointer can be a data race. This method is mostly useful for FFI, where the function signature may use
*mut *mut Tinstead of&AtomicPtr<T>.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. All modifications of an atomic change the value through a shared reference, and can do so safely as long as they use atomic operations. Any use of the returned raw pointer requires anunsafeblock and still has to uphold the requirements of the memory model.Examples
use std::sync::atomic::AtomicPtr; extern "C" { fn my_atomic_op(arg: *mut *mut u32); } let mut value = 17; let atomic = AtomicPtr::new(&mut value); // SAFETY: Safe as long as `my_atomic_op` is atomic. unsafe { my_atomic_op(atomic.as_ptr()); }
Trait Implementations
impl<T: AtomicPrimitive> Send for Atomic<T>
impl<T: AtomicPrimitive> Sync for Atomic<T>
Auto Trait Implementations
impl<T> !Freeze for Atomic<T>
impl<T> Unpin for Atomic<T>
where
UnsafeCell<<T as AtomicPrimitive>::Storage>: Unpin,
impl<T> UnsafeUnpin for Atomic<T>
where
UnsafeCell<<T as AtomicPrimitive>::Storage>: UnsafeUnpin,
impl<T> UnwindSafe for Atomic<T>
where
UnsafeCell<<T as AtomicPrimitive>::Storage>: UnwindSafe,
Blanket Implementations
impl<T> Any for Atomic<T>
where
T: 'static + ?Sized,
fn type_id(&self) -> TypeId
impl<T> Borrow<T> for Atomic<T>
where
T: ?Sized,
fn borrow(&self) -> &T
impl<T> BorrowMut<T> for Atomic<T>
where
T: ?Sized,
fn borrow_mut(&mut self) -> &mut T
impl<T> From<T> for Atomic<T>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> SizeHint for Atomic<T>
where
T: ?Sized,
fn lower_bound(&self) -> usizefn upper_bound(&self) -> Option<usize>
impl<T> SizedTypeProperties for Atomic<T>
impl<T, U> Into<U> for Atomic<T>
where
U: From<T>,
fn into(self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom<U> for Atomic<T>
where
U: Into<T>,
type Error = never;fn try_from(value: U) -> Result<T, never>
impl<T, U> TryInto<U> for Atomic<T>
where
U: TryFrom<T>,
type Error = <U as TryFrom<T>>::Error;fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>