WeCodeAcademy

Rust Threads

Rust's ownership rules make threads safe. Use thread::spawn to start one, join to wait for it, Arc<Mutex<T>> to share data, and channels to send messages.

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

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

    let (tx, rx) = mpsc::channel();
    let worker = thread::spawn(move || {
        for i in 1..=3 {
            tx.send(i * i).unwrap();
        }
    });
    worker.join().unwrap();
    for v in rx {
        println!("received {}", v);
    }
}
Output
total 8000
received 1
received 4
received 9
Quick check

What do Arc<Mutex<T>> give you together?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.