RsRust
AdvancedLesson 16 of 16

Concurrency: Threads, Channels, Mutex – Rust

Fearless concurrency: Rust prevents data races at compile time.

Rust uses operating system threads via std::thread. spawn starts a thread, and join waits for it and returns its result. Because the thread can outlive the calling function, the closure must take over its data with move.

use std::thread;

fn main() {
    let daten = vec![1, 2, 3];
    let h = thread::spawn(move || daten.iter().sum::<i32>());
    println!("{}", h.join().unwrap());   // 6
}

Channels (mpsc = multiple producer, single consumer) send messages between threads. Sending transfers ownership: after the send, the value belongs to the receiver. The motto: *“Share memory by communicating.”*

use std::sync::mpsc;
use std::thread;

fn main() {
    let (tx, rx) = mpsc::channel();
    for id in 0..3 {
        let tx = tx.clone();
        thread::spawn(move || {
            tx.send(id * 10).unwrap();
        });
    }
    drop(tx);                       // close the original sender, otherwise rx never ends
    let mut ergebnisse: Vec<i32> = rx.iter().collect();
    ergebnisse.sort();
    println!("{:?}", ergebnisse);   // [0, 10, 20]
}

For shared mutable state you need Arc<Mutex<T>>: Arc (atomic reference counter) allows multiple owners across threads, and Mutex lets only one thread access the data at a time. The MutexGuard releases the lock automatically when it goes out of scope.

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

fn main() {
    let zaehler = Arc::new(Mutex::new(0));
    let mut handles = vec![];
    for _ in 0..8 {
        let z = Arc::clone(&zaehler);
        handles.push(thread::spawn(move || {
            *z.lock().unwrap() += 1;
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    println!("{}", *zaehler.lock().unwrap());   // 8
}

Two marker traits make this safe: Send (a value may be moved to another thread) and Sync (&T may be used by several threads). Rc and RefCell are neither Send nor Sync, so the compiler rejects using them across threads. This turns data races into compiler errors.

Since Rust 1.63 there are scoped threads, which may borrow local variables because the scope is guaranteed to wait for all threads:

use std::thread;

fn main() {
    let mut zahlen = vec![1, 2, 3];
    thread::scope(|s| {
        s.spawn(|| println!("Length: {}", zahlen.len()));
    });
    zahlen.push(4);                 // freely usable again
    println!("{:?}", zahlen);
}
TipFor data-parallel loops use the rayon crate (par_iter()), and for asynchronous I/O (many network connections) use async/await with a runtime such as tokio. For simple counters, std::sync::atomic::AtomicUsize and friends are faster than a mutex.
WarningA Mutex can still cause a deadlock (two threads waiting for each other), and lock() returns a Result (poisoning after a panic). Rust prevents data races, but not logic errors.