Struct AtomicPtr
struct AtomicPtr<T> { ... }
A raw pointer type which can be safely shared between threads.
This type has the same size and bit validity as a *mut T.
Note: This type is only available on platforms that support atomic loads and stores of pointers. Its size depends on the target pointer's size.
Implementations
impl<T> AtomicPtr<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>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).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.fetch_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.fetch_update; assert_eq!; assert_eq!;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 AtomicPtr<T>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for AtomicPtr<T>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for AtomicPtr<T>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> Debug for AtomicPtr<T>
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl<T> Default for AtomicPtr<T>
fn default() -> AtomicPtr<T>Creates a null
AtomicPtr<T>.
impl<T> Freeze for AtomicPtr<T>
impl<T> From for AtomicPtr<T>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> From for AtomicPtr<T>
fn from(p: *mut T) -> SelfConverts a
*mut Tinto anAtomicPtr<T>.
impl<T> Pointer for AtomicPtr<T>
fn fmt(self: &Self, f: &mut fmt::Formatter<'_>) -> fmt::Result
impl<T> RefUnwindSafe for crate::sync::atomic::AtomicPtr<T>
impl<T> Send for AtomicPtr<T>
impl<T> Sync for AtomicPtr<T>
impl<T> Unpin for AtomicPtr<T>
impl<T> UnwindSafe for AtomicPtr<T>
impl<T, U> Into for AtomicPtr<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 AtomicPtr<T>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for AtomicPtr<T>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>