Atomics
Recipe | Crates | Categories |
---|---|---|
Standard Atomic Types | ||
arc-swap |
Standard Atomic Types
Atomic types in std::sync::atomic
⮳ provide primitive shared-memory communication between threads, and are the building blocks of other concurrent types. It defines atomic versions of a select number of primitive types, including std::sync::atomic::AtomicBool
⮳, std::sync::atomic::AtomicIsize
⮳, std::sync::atomic::AtomicUsize
⮳, std::sync::atomic::AtomicI8
⮳, std::sync::atomic::AtomicU16
⮳, etc.
use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; static GLOBAL_THREAD_COUNT: AtomicUsize = AtomicUsize::new(0); fn main() { let old_thread_count = GLOBAL_THREAD_COUNT.fetch_add(1, Ordering::SeqCst); println!("live threads: {}", old_thread_count + 1); }
The most common way to share an atomic variable is to put it into an std::sync::Arc
⮳ (an atomically-reference-counted shared pointer).
crossbeam
⮳ also offers crossbeam::atomic::AtomicCell
⮳, a thread-safe mutable memory location. This type is equivalent to std::cell::Cell
⮳, except it can also be shared among multiple threads.
use crossbeam_utils::atomic::AtomicCell; fn main() { let a = AtomicCell::new(7); let v = a.into_inner(); assert_eq!(v, 7); println!("{}", v); }
Atomic Operations
std::sync::atomic
⮳ provides atomic types for safe concurrent access to data. Essential for multi-threaded programming.
arc-swap
The ArcSwap
type in arc-swap
⮳ is a container for an Arc
that can be changed atomically. Semantically, it is similar to Atomic<Arc<T>>
(if there was such a thing) or RwLock<Arc<T>>
(but without the need for the locking). It is optimized for read-mostly scenarios, with consistent performance characteristics.