Atomic Types
Use atomic types for lock-free concurrent programming.
Atomic Types
Use atomic types for lock-free concurrent programming.
Difficulty
Advanced
Code
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::thread;
fn main() {
let counter = Arc::new(AtomicUsize::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
handles.push(thread::spawn(move || {
for _ in 0..1000 {
counter.fetch_add(1, Ordering::SeqCst);
}
}));
}
for h in handles { h.join().unwrap(); }
println!("counter: {}", counter.load(Ordering::SeqCst));
}Explanation
Atomic types provide lock-free concurrent operations.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the concurrency category to build a complete understanding of this topic.