Struct AtomicBool
struct AtomicBool { ... }
A boolean type which can be safely shared between threads.
This type has the same in-memory representation as a bool.
If the compiler and the platform support atomic loads and stores of u8,
this type is a wrapper for the standard library's
AtomicBool. If the platform supports it
but the compiler does not, atomic operations are implemented using inline
assembly.
Implementations
impl AtomicBool
const fn new(v: bool) -> SelfCreates a new
AtomicBool.Examples
use AtomicBool; let atomic_true = new; let atomic_false = new;unsafe const fn from_ptr<'a>(ptr: *mut bool) -> &'a SelfCreates a new
AtomicBoolfrom a pointer.This is
const fnon Rust 1.83+.Safety
ptrmust be aligned toalign_of::<AtomicBool>()(note that on some platforms this can be bigger thanalign_of::<bool>()).ptrmust be valid for both reads and writes for the whole lifetime'a.- If this atomic type is lock-free, non-atomic accesses to the value
behind
ptrmust have a happens-before relationship with atomic accesses via the returned value (or vice-versa).- In other words, time periods where the value is accessed atomically may not overlap with periods where the value is accessed non-atomically.
- This requirement is trivially satisfied if
ptris never used non-atomically for the duration of lifetime'a. Most use cases should be able to follow this guideline. - This requirement is also trivially satisfied if all accesses (atomic or not) are done from the same thread.
- If this atomic type is not lock-free:
- Any accesses to the value behind
ptrmust have a happens-before relationship with accesses via the returned value (or vice-versa). - Any concurrent accesses to the value behind
ptrfor the duration of lifetime'amust be compatible with operations performed by this atomic type.
- Any accesses to the value behind
- This method must not be used to create overlapping or mixed-size atomic accesses, as these are not supported by the memory model.
fn is_lock_free() -> boolReturns
trueif operations on values of this type are lock-free.If the compiler or the platform doesn't support the necessary atomic instructions, global locks for every potentially concurrent atomic operation will be used.
Examples
use AtomicBool; let is_lock_free = is_lock_free;const fn is_always_lock_free() -> boolReturns
trueif operations on values of this type are lock-free.If the compiler or the platform doesn't support the necessary atomic instructions, global locks for every potentially concurrent atomic operation will be used.
Note: If the atomic operation relies on dynamic CPU feature detection, this type may be lock-free even if the function returns false.
Examples
use AtomicBool; const IS_ALWAYS_LOCK_FREE: bool = is_always_lock_free;const 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.
This is
const fnon Rust 1.83+.Examples
use ; let mut some_bool = new; assert_eq!; *some_bool.get_mut = false; 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.This is
const fnon Rust 1.56+.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.Examples
use ; let some_bool = new; 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.Panics
Panics if
failureisRelease,AcqRel.Examples
use ; let some_bool = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;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.Panics
Panics if
failureisRelease,AcqRel.Examples
use ; let val = new; let new = true; let mut old = val.load; loopfn 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.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;fn and(self: &Self, val: bool, order: Ordering)Logical "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.Unlike
fetch_and, this does not return the previous value.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.This function may generate more efficient code than
fetch_andon some platforms.- x86/x86_64:
lock andinstead ofcmpxchgloop - MSP430:
andinstead of disabling interrupts
Note: On x86/x86_64, the use of either function should not usually affect the generated code, because LLVM can properly optimize the case where the result is unused.
Examples
use ; let foo = new; foo.and; assert_eq!; let foo = new; foo.and; assert_eq!; let foo = new; foo.and; assert_eq!;- x86/x86_64:
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.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.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;fn or(self: &Self, val: bool, order: Ordering)Logical "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.Unlike
fetch_or, this does not return the previous value.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.This function may generate more efficient code than
fetch_oron some platforms.- x86/x86_64:
lock orinstead ofcmpxchgloop - MSP430:
bisinstead of disabling interrupts
Note: On x86/x86_64, the use of either function should not usually affect the generated code, because LLVM can properly optimize the case where the result is unused.
Examples
use ; let foo = new; foo.or; assert_eq!; let foo = new; foo.or; assert_eq!; let foo = new; foo.or; assert_eq!;- x86/x86_64:
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.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;fn xor(self: &Self, val: bool, order: Ordering)Logical "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.Unlike
fetch_xor, this does not return the previous value.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.This function may generate more efficient code than
fetch_xoron some platforms.- x86/x86_64:
lock xorinstead ofcmpxchgloop - MSP430:
xorinstead of disabling interrupts
Note: On x86/x86_64, the use of either function should not usually affect the generated code, because LLVM can properly optimize the case where the result is unused.
Examples
use ; let foo = new; foo.xor; assert_eq!; let foo = new; foo.xor; assert_eq!; let foo = new; foo.xor; assert_eq!;- x86/x86_64:
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.Examples
use ; let foo = new; assert_eq!; assert_eq!; let foo = new; assert_eq!; assert_eq!;fn not(self: &Self, order: Ordering)Logical "not" with a boolean value.
Performs a logical "not" operation on the current value, and sets the new value to the result.
Unlike
fetch_not, this does not return the previous value.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.This function may generate more efficient code than
fetch_noton some platforms.- x86/x86_64:
lock xorinstead ofcmpxchgloop - MSP430:
xorinstead of disabling interrupts
Note: On x86/x86_64, the use of either function should not usually affect the generated code, because LLVM can properly optimize the case where the result is unused.
Examples
use ; let foo = new; foo.not; assert_eq!; let foo = new; foo.not; assert_eq!;- x86/x86_64:
fn fetch_update<F>(self: &Self, set_order: Ordering, fetch_order: Ordering, f: F) -> Result<bool, bool> where F: FnMut(bool) -> Option<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).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 ofcompare_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.Considerations
This method is not magic; it is not provided by the hardware. It is implemented in terms of
compare_exchange_weak, and suffers from the same drawbacks. In particular, this method will not circumvent the ABA Problem.Panics
Panics if
fetch_orderisRelease,AcqRel.Examples
use ; let x = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!;const fn as_ptr(self: &Self) -> *mut boolReturns a mutable pointer to the underlying
bool.Returning an
*mutpointer from a shared reference to this atomic is safe because the atomic types work with interior mutability. Any use of the returned raw pointer requires anunsafeblock and has to uphold the safety requirements. If there is concurrent access, note the following additional safety requirements:- If this atomic type is lock-free, any concurrent operations on it must be atomic.
- Otherwise, any concurrent operations on it must be compatible with operations performed by this atomic type.
This is
const fnon Rust 1.58+.
impl Debug for AtomicBool
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl Default for AtomicBool
fn default() -> SelfCreates an
AtomicBoolinitialized tofalse.
impl Freeze for AtomicBool
impl From for AtomicBool
fn from(b: bool) -> SelfConverts a
boolinto anAtomicBool.
impl RefUnwindSafe for AtomicBool
impl Send for AtomicBool
impl Sync for AtomicBool
impl Unpin for AtomicBool
impl UnsafeUnpin for AtomicBool
impl UnwindSafe for AtomicBool
impl<T> Any for AtomicBool
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for AtomicBool
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for AtomicBool
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for AtomicBool
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for AtomicBool
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 AtomicBool
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for AtomicBool
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>