Threading

Rust's borrowing model allows writing thread-safe abstractions like a mutex.

This allows safely mutating a value through a shared reference.

use std::sync::{Arc, Mutex};
use std::rc::Rc;
use std::thread;
use std::time::Duration;

fn main() {
    // Create a reference-counted, mutex-protected integer
    let value = Arc::new(Mutex::new(0));

    // Create another reference to the integer and move it onto another thread
    let cloned_value = value.clone();
    thread::spawn(move || {
        // Lock the mutex
        let mut lock_guard = cloned_value.lock().unwrap();

        // Since the mutex is locked, we can safely get a `&mut` reference to
        // mutate the integer
        *lock_guard = 1;

        // The mutex is unlocked when `lock_guard` goes out of scope
    });

    println!("{}", value.lock().unwrap());
    thread::sleep(Duration::from_millis(20));
    println!("{}", value.lock().unwrap());
}

Note this is safe because the Arc type uses atomic operations for reference counting, so it can be used from multiple threads. This is described by the Send trait. If we use the non-atomic version, we get an error.