Atomic types in Rust are specialized data types designed for safe concurrent programming. They provide thread-safe operations without the need for explicit locking mechanisms.
Atomic types ensure that operations on shared data are performed atomically, meaning they appear to occur instantaneously to other threads. This is crucial for maintaining data consistency in multi-threaded environments.
AtomicBool
: For boolean valuesAtomicI32
, AtomicU32
: For 32-bit integersAtomicI64
, AtomicU64
: For 64-bit integersAtomicUsize
, AtomicIsize
: For pointer-sized integersTo use atomic types, import them from the std::sync::atomic
module. Here's a simple example using AtomicBool
:
use std::sync::atomic::{AtomicBool, Ordering};
let flag = AtomicBool::new(false);
flag.store(true, Ordering::SeqCst);
let value = flag.load(Ordering::SeqCst);
Atomic operations require specifying an Ordering
, which determines the memory synchronization guarantees. Common orderings include:
Ordering::Relaxed
: No synchronizationOrdering::SeqCst
: Strongest guarantees, ensures sequential consistencyOrdering::Acquire
: Used for loading operationsOrdering::Release
: Used for storing operationsAtomic types support various operations:
load()
: Read the current valuestore()
: Set a new valuecompare_and_swap()
: Compare and set if equalfetch_add()
, fetch_sub()
: Atomic arithmetic operationsHere's an example of using AtomicUsize
as a thread-safe counter:
use std::sync::atomic::{AtomicUsize, Ordering};
use std::thread;
let counter = AtomicUsize::new(0);
let handles: Vec<_> = (0..10).map(|_| {
let counter = &counter;
thread::spawn(move || {
for _ in 0..1000 {
counter.fetch_add(1, Ordering::SeqCst);
}
})
}).collect();
for handle in handles {
handle.join().unwrap();
}
println!("Final count: {}", counter.load(Ordering::SeqCst));
To deepen your understanding of concurrent programming in Rust, explore these related topics:
Mastering atomic types is crucial for writing efficient and safe concurrent Rust code. They provide a powerful tool for managing shared state without the overhead of locks.