RRust By Example
advancedConcurrency

Arc and Mutex

Share state between threads safely with Arc<Mutex<T>>.

Arc and Mutex

Share state between threads safely with Arc>.

Difficulty

Advanced

Code

rust
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

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

    for handle in handles {
        handle.join().unwrap();
    }

    println!("result: {}", *counter.lock().unwrap());
}

Explanation

Arc> enables shared mutable state across threads.

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.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Concurrency Examples