ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Rust Tutorial• 8 min read

Fearless Concurrency: Threads, Arc & Mutex

thread::spawn, move closures, and thread-safe shared state with Arc<Mutex<T>>

Rust terms its multithreading model "Fearless Concurrency" because ownership and type system rules prevent data races at compile time before your code ever runs.

Arc and Mutex for Thread-Safe Shared State

std::thread::spawn: Spawns a native OS thread. The move keyword forces the closure to take ownership of captured variables.

Mutex<T> (Mutual Exclusion): Guarantees only one thread can access data at a time. Call .lock().unwrap() to access the data.

Arc<T> (Atomic Reference Counting): Allows thread-safe shared ownership across multiple OS threads.

Multi-Threaded Counter with Arc and Mutex
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    // Atomically reference-counted Mutex protecting a counter
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..5 {
        let counter_clone = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter_clone.lock().unwrap();
            *num += 1;
        });
        handles.push(handle);
    }

    // Wait for all threads to complete
    for handle in handles {
        handle.join().unwrap();
    }

    println!("Final Counter Result: {}", *counter.lock().unwrap()); // 5
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which smart pointer type provides thread-safe atomic reference counting to share data across multiple threads in Rust?