RRust By Example
advancedConcurrency

Atomic Types

Use atomic types for lock-free concurrent programming.

Atomic Types

Use atomic types for lock-free concurrent programming.

Difficulty

Advanced

Code

rust
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

This example demonstrates how to use atomic types in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the concurrency category to build a complete understanding of this topic.

More Concurrency Examples