pub struct AtomicBool { /* private fields */ }Expand description
Atomic boolean type.
Provides easy-to-use atomic operations with automatic memory ordering selection. All methods are thread-safe and can be shared across threads.
§Memory Ordering Strategy
This type uses carefully selected default memory orderings:
-
Read operations (
load): UseAcquireordering to ensure that all writes from other threads that happened before aReleasestore are visible after this load. -
Write operations (
store): UseReleaseordering to ensure that all prior writes in this thread are visible to other threads that perform anAcquireload. -
Read-Modify-Write operations (
swap,compare_set,fetch_*): UseAcqRelordering to combine bothAcquireandReleasesemantics, ensuring proper synchronization in both directions. -
CAS failure: Use
Acquireordering on failure to observe the actual value written by another thread.
These orderings provide a balance between performance and correctness for typical concurrent programming patterns.
§Features
- Automatic memory ordering selection
- Rich set of boolean-specific operations
- Zero-cost abstraction with inline methods
- Access to underlying type via
inner()for advanced use cases
§Example
use qubit_atomic::Atomic;
use std::sync::Arc;
use std::thread;
let flag = Arc::new(Atomic::<bool>::new(false));
let flag_clone = flag.clone();
let handle = thread::spawn(move || {
flag_clone.store(true);
});
handle.join().unwrap();
assert_eq!(flag.load(), true);Implementations§
Source§impl AtomicBool
impl AtomicBool
Sourcepub fn load(&self) -> bool
pub fn load(&self) -> bool
Gets the current value.
§Memory Ordering
Uses Acquire ordering. This ensures that:
- All writes from other threads that happened before a
Releasestore are visible after this load. - Forms a synchronizes-with relationship with
Releasestores. - Prevents reordering of subsequent reads/writes before this load.
This is appropriate for reading shared state that may have been modified by other threads.
§Returns
The current value.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(true);
assert_eq!(flag.load(), true);Sourcepub fn store(&self, value: bool)
pub fn store(&self, value: bool)
Sets a new value.
§Memory Ordering
Uses Release ordering. This ensures that:
- All prior writes in this thread are visible to other threads that
perform an
Acquireload. - Forms a synchronizes-with relationship with
Acquireloads. - Prevents reordering of prior reads/writes after this store.
This is appropriate for publishing shared state to other threads.
§Parameters
value- The new value to set.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
flag.store(true);
assert_eq!(flag.load(), true);Sourcepub fn swap(&self, value: bool) -> bool
pub fn swap(&self, value: bool) -> bool
Swaps the current value with a new value, returning the old value.
§Memory Ordering
Uses AcqRel ordering. This ensures that:
- Acquire: All writes from other threads that happened before
their
Releaseoperations are visible after this operation. - Release: All prior writes in this thread are visible to other
threads that perform subsequent
Acquireoperations.
This provides full synchronization for read-modify-write operations.
§Parameters
value- The new value to swap in.
§Returns
The old value.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
let old = flag.swap(true);
assert_eq!(old, false);
assert_eq!(flag.load(), true);Sourcepub fn compare_set(&self, current: bool, new: bool) -> Result<(), bool>
pub fn compare_set(&self, current: bool, new: bool) -> Result<(), bool>
Compares and sets the value atomically.
If the current value equals current, sets it to new and returns
Ok(()). Otherwise, returns Err(actual) where actual is the
current value.
§Memory Ordering
- Success: Uses
AcqRelordering to ensure full synchronization when the exchange succeeds. - Failure: Uses
Acquireordering to observe the actual value written by another thread.
This pattern is essential for implementing lock-free algorithms where you need to retry based on the observed value.
§Parameters
current- The expected current value.new- The new value to set if current matches.
§Returns
Ok(()) when the value was replaced.
§Errors
Returns Err(actual) with the observed value when the comparison
fails. In that case, new is not stored.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert!(flag.compare_set(false, true).is_ok());
assert_eq!(flag.load(), true);
// Fails because current value is true, not false
assert!(flag.compare_set(false, false).is_err());Sourcepub fn compare_set_weak(&self, current: bool, new: bool) -> Result<(), bool>
pub fn compare_set_weak(&self, current: bool, new: bool) -> Result<(), bool>
Weak version of compare-and-set.
May spuriously fail even when the comparison succeeds. Should be used in a loop.
Uses AcqRel ordering on success and Acquire ordering on failure.
§Parameters
current- The expected current value.new- The new value to set if current matches.
§Returns
Ok(()) when the value was replaced.
§Errors
Returns Err(actual) with the observed value when the comparison
fails, including possible spurious failures. In that case, new is not
stored.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
let mut current = flag.load();
loop {
match flag.compare_set_weak(current, true) {
Ok(_) => break,
Err(actual) => current = actual,
}
}
assert_eq!(flag.load(), true);Sourcepub fn compare_and_exchange(&self, current: bool, new: bool) -> bool
pub fn compare_and_exchange(&self, current: bool, new: bool) -> bool
Compares and exchanges the value atomically, returning the previous value.
If the current value equals current, sets it to new and returns
the old value. Otherwise, returns the actual current value.
Uses AcqRel ordering on success and Acquire ordering on failure.
§Parameters
current- The expected current value.new- The new value to set if current matches.
§Returns
The value observed before the operation completed. If the returned
value equals current, the exchange succeeded; otherwise it is the
actual value that prevented the exchange.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
let prev = flag.compare_and_exchange(false, true);
assert_eq!(prev, false);
assert_eq!(flag.load(), true);Sourcepub fn compare_and_exchange_weak(
&self,
current: bool,
new: bool,
) -> Result<bool, bool>
pub fn compare_and_exchange_weak( &self, current: bool, new: bool, ) -> Result<bool, bool>
Weak version of compare-and-exchange.
May spuriously fail even when the comparison succeeds. Should be used in a loop.
Uses AcqRel ordering on success and Acquire ordering on failure.
§Parameters
current- The expected current value.new- The new value to set if current matches.
§Returns
Ok(previous) when the value was replaced, or Err(actual) when the
comparison failed, including possible spurious failure.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
let mut current = flag.load();
loop {
match flag.compare_and_exchange_weak(current, true) {
Ok(previous) => {
assert_eq!(previous, current);
break;
}
Err(actual) => current = actual,
}
}
assert_eq!(flag.load(), true);Sourcepub fn fetch_set(&self) -> bool
pub fn fetch_set(&self) -> bool
Atomically sets the value to true, returning the old value.
§Memory Ordering
Uses AcqRel ordering (via swap). This ensures full
synchronization with other threads for this read-modify-write
operation.
§Returns
The old value before setting to true.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
let old = flag.fetch_set();
assert_eq!(old, false);
assert_eq!(flag.load(), true);Sourcepub fn fetch_clear(&self) -> bool
pub fn fetch_clear(&self) -> bool
Atomically sets the value to false, returning the old value.
§Memory Ordering
Uses AcqRel ordering (via swap). This ensures full
synchronization with other threads for this read-modify-write
operation.
§Returns
The old value before setting to false.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(true);
let old = flag.fetch_clear();
assert_eq!(old, true);
assert_eq!(flag.load(), false);Sourcepub fn fetch_not(&self) -> bool
pub fn fetch_not(&self) -> bool
Atomically negates the value, returning the old value.
§Memory Ordering
Uses AcqRel ordering. This ensures full synchronization with other
threads for this read-modify-write operation.
§Returns
The old value before negation.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert_eq!(flag.fetch_not(), false);
assert_eq!(flag.load(), true);
assert_eq!(flag.fetch_not(), true);
assert_eq!(flag.load(), false);Sourcepub fn fetch_and(&self, value: bool) -> bool
pub fn fetch_and(&self, value: bool) -> bool
Atomically performs logical AND, returning the old value.
§Memory Ordering
Uses AcqRel ordering. This ensures full synchronization with other
threads for this read-modify-write operation, which is necessary
because the operation depends on the current value.
§Parameters
value- The value to AND with.
§Returns
The old value before the operation.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(true);
assert_eq!(flag.fetch_and(false), true);
assert_eq!(flag.load(), false);Sourcepub fn fetch_or(&self, value: bool) -> bool
pub fn fetch_or(&self, value: bool) -> bool
Atomically performs logical OR, returning the old value.
§Memory Ordering
Uses AcqRel ordering. This ensures full synchronization with other
threads for this read-modify-write operation, which is necessary
because the operation depends on the current value.
§Parameters
value- The value to OR with.
§Returns
The old value before the operation.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert_eq!(flag.fetch_or(true), false);
assert_eq!(flag.load(), true);Sourcepub fn fetch_xor(&self, value: bool) -> bool
pub fn fetch_xor(&self, value: bool) -> bool
Atomically performs logical XOR, returning the old value.
§Memory Ordering
Uses AcqRel ordering. This ensures full synchronization with other
threads for this read-modify-write operation, which is necessary
because the operation depends on the current value.
§Parameters
value- The value to XOR with.
§Returns
The old value before the operation.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert_eq!(flag.fetch_xor(true), false);
assert_eq!(flag.load(), true);Sourcepub fn set_if_false(&self, new: bool) -> Result<(), bool>
pub fn set_if_false(&self, new: bool) -> Result<(), bool>
Conditionally sets the value if it is currently false.
Uses AcqRel ordering on success and Acquire ordering on failure.
§Parameters
new- The new value to set if current isfalse.
§Returns
Ok(()) if the value was false and has been set to new.
§Errors
Returns Err(true) if the value was already true. In that case,
new is not stored.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert!(flag.set_if_false(true).is_ok());
assert_eq!(flag.load(), true);
// Second attempt fails
assert!(flag.set_if_false(true).is_err());Sourcepub fn set_if_true(&self, new: bool) -> Result<(), bool>
pub fn set_if_true(&self, new: bool) -> Result<(), bool>
Conditionally sets the value if it is currently true.
Uses AcqRel ordering on success and Acquire ordering on failure.
§Parameters
new- The new value to set if current istrue.
§Returns
Ok(()) if the value was true and has been set to new.
§Errors
Returns Err(false) if the value was already false. In that case,
new is not stored.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(true);
assert!(flag.set_if_true(false).is_ok());
assert_eq!(flag.load(), false);
// Second attempt fails
assert!(flag.set_if_true(false).is_err());Sourcepub fn fetch_update<F>(&self, f: F) -> bool
pub fn fetch_update<F>(&self, f: F) -> bool
Updates the value using a function, returning the old value.
Internally uses a CAS loop until the update succeeds.
§Parameters
f- A function that takes the current value and returns the new value.
§Returns
The old value before the update.
The closure may be called more than once when concurrent updates cause CAS retries.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert_eq!(flag.fetch_update(|current| !current), false);
assert_eq!(flag.load(), true);Sourcepub fn update_and_get<F>(&self, f: F) -> bool
pub fn update_and_get<F>(&self, f: F) -> bool
Updates the value using a function, returning the new value.
Internally uses a CAS loop until the update succeeds.
§Parameters
f- A function that takes the current value and returns the new value.
§Returns
The value committed by the successful update.
The closure may be called more than once when concurrent updates cause CAS retries.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert_eq!(flag.update_and_get(|current| !current), true);
assert_eq!(flag.load(), true);Sourcepub fn try_update<F>(&self, f: F) -> Option<bool>
pub fn try_update<F>(&self, f: F) -> Option<bool>
Conditionally updates the value using a function.
Internally uses a CAS loop until the update succeeds or the closure
rejects the current value by returning None.
§Parameters
f- A function that takes the current value and returns the new value, orNoneto leave the value unchanged.
§Returns
Some(old_value) when the update succeeds, or None when f rejects
the observed current value.
The closure may be called more than once when concurrent updates cause CAS retries.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert_eq!(flag.try_update(|current| (!current).then_some(true)), Some(false));
assert_eq!(flag.load(), true);
assert_eq!(flag.try_update(|current| (!current).then_some(true)), None);
assert_eq!(flag.load(), true);Sourcepub fn try_update_and_get<F>(&self, f: F) -> Option<bool>
pub fn try_update_and_get<F>(&self, f: F) -> Option<bool>
Conditionally updates the value using a function, returning the new value.
Internally uses a CAS loop until the update succeeds or the closure
rejects the current value by returning None.
§Parameters
f- A function that takes the current value and returns the new value, orNoneto leave the value unchanged.
§Returns
Some(new_value) when the update succeeds, or None when f rejects
the observed current value.
The closure may be called more than once when concurrent updates cause CAS retries.
§Example
use qubit_atomic::Atomic;
let flag = Atomic::<bool>::new(false);
assert_eq!(
flag.try_update_and_get(|current| (!current).then_some(true)),
Some(true),
);
assert_eq!(flag.load(), true);
assert_eq!(
flag.try_update_and_get(|current| (!current).then_some(true)),
None,
);
assert_eq!(flag.load(), true);Sourcepub fn inner(&self) -> &StdAtomicBool
pub fn inner(&self) -> &StdAtomicBool
Gets a reference to the underlying standard library atomic type.
This allows direct access to the standard library’s atomic operations for advanced use cases that require fine-grained control over memory ordering.
§Memory Ordering
When using the returned reference, you have full control over memory ordering. Choose the appropriate ordering based on your specific synchronization requirements.
§Returns
A reference to the underlying std::sync::atomic::AtomicBool.
§Example
use qubit_atomic::Atomic;
use std::sync::atomic::Ordering;
let flag = Atomic::<bool>::new(false);
flag.inner().store(true, Ordering::Relaxed);
assert_eq!(flag.inner().load(Ordering::Relaxed), true);