1 unstable release
0.1.0 | Jan 18, 2025 |
---|
#207 in Date and time
149 downloads per month
25KB
169 lines
atomic_instant_full
This crate provides an AtomicInstant
type, which acts as an almost complete wrapper around AtomicUsize
and Instant
. It offers atomic operations on an Instant
value, allowing you to safely update the value from multiple threads while maintaining consistency.
Features
- Atomicity: Ensures that updates to the
Instant
value are atomic, preventing data races. - Safety: The
AtomicInstant
type enforces invariants to prevent unexpected behavior. - Convenience: Provides various methods for updating, comparing, and fetching the
Instant
value with different memory ordering guarantees.
Usage
A large majority of the features of AtomicUsize have been ported over to AtomicInstant in an attempt to make it as easy as possible to use.
However, the main limitation of this implementation is that nothing is signed. This means that functions such as fetch_sub and fetch_min may not operate correctly
use atomic_instant_full::AtomicInstant;
use std::time::Instant;
// Create a new AtomicInstant from an Instant
let now = Instant::now();
let atomic_instant = AtomicInstant::new(now);
// Update the AtomicInstant if the current value is equal to the expected value
let new_instant = now + Duration::from_secs(5);
let result = atomic_instant.compare_exchange(now, new_instant, Ordering::Acquire, Ordering::Relaxed);
// Check the result of the compare_exchange operation
match result {
Ok(instant) => println!("Successfully updated to {:?}", instant),
Err(current) => println!("Failed to update, current value is {:?}", current),
}
// Load the current value of the AtomicInstant
let current_instant = atomic_instant.load(Ordering::Relaxed);