#instant #atomic #time

atomic-instant-full

A wrapper around Instant and AtomicUsize to implement most of the features of AtomicUsize

1 unstable release

0.1.0 Jan 18, 2025

#207 in Date and time

Download history 107/week @ 2025-01-13 42/week @ 2025-01-20

149 downloads per month

MIT license

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);

No runtime deps

Features