Sub topic 1
Concurrency, threads, and what Rust guarantees
Prerequisites
This chapter assumes you know Rust ownership, borrowing, and lifetimes. You should also be comfortable with closures and the move keyword, with Result, Option, and unwrap, and with basic traits and generics. You need cargo to build and run the examples.
Concurrency and threads
Concurrency means a program makes progress on more than one task during the same period. Parallelism means two tasks run at the same instant on different CPU cores. Threads give you both. The operating system schedules them and runs them on whatever cores are available.
Rust's standard library uses OS threads. Each std::thread::spawn call asks the operating system for a new thread with its own stack. This is a 1:1 model, where one Rust thread maps to one OS thread. Rust does not ship a green-thread runtime in the standard library.
Every program starts with one thread, the main thread. When main returns, the process ends, even if other threads are still running.
use std::thread;
fn main() {
let handle = thread::spawn(|| (1..=5).sum::<u32>());
let total = handle.join().unwrap();
println!("total = {total}");
}spawn starts a new thread and returns a JoinHandle. Calling join blocks the current thread until the spawned thread finishes. It returns a Result holding the thread's return value. Later chapters cover spawn and join in detail. Here the example shows that a thread is just a closure running somewhere else.
Why threads are hard
Two threads that touch the same memory can interfere with each other. A data race happens when all three of these are true:
- Two or more threads access the same memory location.
- At least one access is a write.
- Nothing orders the accesses, such as a lock.
In many languages, a data race is a bug you find at run time, if you find it at all. The results vary from run to run, which makes the bug hard to reproduce.
What Rust guarantees
Safe Rust makes data races a compile-time error. You do not need a special checker. The guarantee comes from rules you already know:
- Ownership means each value has one owner. Moving a value into a thread hands the thread sole control of it.
- Borrowing means you can have many shared references (
&T) or one mutable reference (&mut T), never both at once. That is the same shape as the data race condition above. - Two marker traits,
SendandSync, describe which types may cross thread boundaries. The compiler checks them for you. A later chapter covers them.
If your code could race, it does not compile. You then choose a safe tool: move the data into one thread, send it through a channel, or protect it with Arc and Mutex. The rest of this tutorial covers those tools.
What this tutorial covers
The next chapters build up in this order:
| Step | Topic |
|---|---|
| 1 | Spawning and joining threads, and why closures use `move` |
| 2 | `Send` and `Sync` |
| 3 | Channels, producers, receiving, and closing |
| 4 | Panics, scoped threads, and bounded channels |
| 5 | Shared state with `Arc` and `Mutex`, a worker pool, and choosing an approach |
Exercise
A data race needs three conditions. Which ones are they, and which Rust rule corresponds to the "at least one write" condition being blocked?
Show answer
Two or more threads access the same memory, at least one access is a write, and nothing orders the accesses. Rust's borrowing rule blocks it: you can have a &mut T only when no other reference exists, so a write never overlaps with other access.
Exercise
In the example above, what does handle.join() return, and why is unwrap needed?
Show answer
It returns a Result holding the thread's return value (here a u32). It is an Err if the thread panicked, so unwrap extracts the value and would panic in that case.