Sub topic 1
Concurrency, threads, and what Rust guarantees
Prerequisites
This chapter assumes Rust ownership, borrowing, lifetimes, closures, move, Result, Option, basic traits, and Cargo.
Concurrency, threads, and what Rust guarantees
Concurrency means making progress on multiple tasks during the same period. A thread is an independent path of execution managed by the operating system. On multiple CPU cores, threads can also run in parallel.
Rust uses ownership and traits to prevent data races at compile time. A data race occurs when threads access the same memory at the same time, at least one access changes it, and there is no synchronization. Rust does not prevent every logical race, such as processing an event in an unexpected order, but it prevents this unsafe memory access.
Spawning threads and joining them
thread::spawn starts an operating-system thread and returns a JoinHandle. Calling join waits for that thread to finish. The result is wrapped in Result because the thread might panic.
use std::thread;
fn main() {
let handle = thread::spawn(|| (1..=5).sum::<u32>());
let total = handle.join().unwrap();
println!("total = {total}");
}The program prints total = 15. If the worker panics, join returns Err instead of silently hiding the failure.
Why thread closures use `move`
A closure passed to spawn usually needs move. The spawned thread can continue after the function that created it returns. Borrowing a local variable could then leave the thread with a dangling reference.
move transfers ownership of captured values into the closure:
use std::thread;
fn main() {
let message = String::from("worker");
let handle = thread::spawn(move || println!("{message}"));
handle.join().unwrap();
}The main thread cannot use message afterward because ownership moved to the worker.
Send and Sync: the rules behind safe threading
Send means a value can be moved safely to another thread. Sync means a type can be shared between threads through a reference. More precisely, T is Sync when &T is Send.
These are marker traits. Rust’s compiler automatically implements them when a type’s contents are safe, and refuses them for types that could cause unsound access. Thread APIs require the appropriate bounds, so unsafe values cannot cross thread boundaries accidentally.
Exercise
What does join provide besides waiting?
Show answer
It returns the thread's result, including an error if the thread panicked.