Struct Atomic
struct Atomic<T: AtomicPrimitive> { ... }
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.
Implementations
impl Atomic<bool>
const fn new(v: bool) -> AtomicBoolCreates a new
AtomicBool.Examples
use AtomicBool; let atomic_true = new; let atomic_false = new;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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)); } });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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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!;fn fetch_not(self: &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: &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: &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<impl FnMut(bool) -> Option<bool>: FnMut(bool) -> Option<bool>>(self: &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<impl FnMut(bool) -> bool: FnMut(bool) -> bool>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(bool) -> bool) -> boolFetches the value, applies a function to it that it return 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<i16>
const fn new(v: i16) -> SelfCreates a new atomic integer.
Examples
use AtomicI16; let atomic_forty_two = new;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(i16) -> Option<i16>: FnMut(i16) -> Option<i16>>(self: &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<impl FnMut(i16) -> i16: FnMut(i16) -> i16>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i16) -> i16) -> i16Fetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(i32) -> Option<i32>: FnMut(i32) -> Option<i32>>(self: &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<impl FnMut(i32) -> i32: FnMut(i32) -> i32>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i32) -> i32) -> i32Fetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(i64) -> Option<i64>: FnMut(i64) -> Option<i64>>(self: &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<impl FnMut(i64) -> i64: FnMut(i64) -> i64>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i64) -> i64) -> i64Fetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });fn from_mut_slice(v: &mut [i8]) -> &mut [Self]Get atomic access to a
&mut [i8]slice.Examples
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(i8) -> Option<i8>: FnMut(i8) -> Option<i8>>(self: &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<impl FnMut(i8) -> i8: FnMut(i8) -> i8>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(i8) -> i8) -> i8Fetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(isize) -> Option<isize>: FnMut(isize) -> Option<isize>>(self: &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<impl FnMut(isize) -> isize: FnMut(isize) -> isize>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(isize) -> isize) -> isizeFetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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<u16>
const fn new(v: u16) -> SelfCreates a new atomic integer.
Examples
use AtomicU16; let atomic_forty_two = new;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(u16) -> Option<u16>: FnMut(u16) -> Option<u16>>(self: &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<impl FnMut(u16) -> u16: FnMut(u16) -> u16>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u16) -> u16) -> u16Fetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(u32) -> Option<u32>: FnMut(u32) -> Option<u32>>(self: &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<impl FnMut(u32) -> u32: FnMut(u32) -> u32>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u32) -> u32) -> u32Fetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(u64) -> Option<u64>: FnMut(u64) -> Option<u64>>(self: &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<impl FnMut(u64) -> u64: FnMut(u64) -> u64>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u64) -> u64) -> u64Fetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });fn from_mut_slice(v: &mut [u8]) -> &mut [Self]Get atomic access to a
&mut [u8]slice.Examples
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(u8) -> Option<u8>: FnMut(u8) -> Option<u8>>(self: &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<impl FnMut(u8) -> u8: FnMut(u8) -> u8>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(u8) -> u8) -> u8Fetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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.
fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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 _)); }) });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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!;fn store(self: &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!;fn swap(self: &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!;fn compare_and_swap(self: &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!;fn compare_exchange(self: &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.fn compare_exchange_weak(self: &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.fn fetch_add(self: &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!;fn fetch_sub(self: &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!;fn fetch_and(self: &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!;fn fetch_nand(self: &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!;fn fetch_or(self: &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!;fn fetch_xor(self: &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: &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<impl FnMut(usize) -> Option<usize>: FnMut(usize) -> Option<usize>>(self: &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<impl FnMut(usize) -> usize: FnMut(usize) -> usize>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(usize) -> usize) -> usizeFetches the value, applies a function to it that it return 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!;fn fetch_max(self: &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!;fn fetch_min(self: &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: &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;unsafe const 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 null() -> AtomicPtr<T>Creates a new
AtomicPtrinitialized with a null pointer.Examples
use ; let atomic_ptr = null; assert!;fn get_mut(self: &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!;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!;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
#![feature(atomic_from_mut)] 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}!"); }); } });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
#![feature(atomic_from_mut)] 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: 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!;fn load(self: &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;fn store(self: &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;fn swap(self: &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: &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: &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: &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: &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<impl FnMut(*mut T) -> Option<*mut T>: FnMut(*mut T) -> Option<*mut T>>(self: &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<impl FnMut(*mut T) -> *mut T: FnMut(*mut T) -> *mut T>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: impl FnMut(*mut T) -> *mut T) -> *mut TFetches the value, applies a function to it that it return 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: &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: &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: &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: &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: &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: &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: &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: &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()); }
impl<T> Any for Atomic<T>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for Atomic<T>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for Atomic<T>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> Freeze for Atomic<T>
impl<T> From for Atomic<T>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> RefUnwindSafe for Atomic<T>
impl<T> Unpin for Atomic<T>
impl<T> UnsafeUnpin for Atomic<T>
impl<T> UnwindSafe for Atomic<T>
impl<T, U> Into for Atomic<T>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for Atomic<T>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for Atomic<T>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>