typestar

Arc and Mutex in Rust

Arc shares ownership across threads; Mutex makes the mutation safe.

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

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = Vec::new();

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

    for h in handles {
        h.join().unwrap();
    }
    println!("{}", *counter.lock().unwrap());
}

How it works

  1. Arc::clone bumps a reference count, not a deep copy.
  2. lock returns a guard that unlocks when dropped.
  3. The guard derefs to the value inside.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
377
Tokens
145
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 1 of 3 in Shared state, step 4 of 15 in Concurrency & async.

← Previous Next →