Sub topic 1
Concurrency, Threads, and What Rust Guarantees
Rust's standard library lets you run code on several operating system threads at once. The compiler checks that this code cannot corrupt shared memory. This chapter covers what a thread is, what goes wrong when threads share data, and which of those problems Rust rules out and which it leaves to you. Later chapters cover the APIs in detail.
Prerequisites
This chapter assumes you already know:
- Rust ownership, borrowing, and lifetimes. You can explain why a value has one owner and why a
&mutborrow is exclusive. - Closures and the
movekeyword. Result,Option, andunwrap.- Basic traits and generics, enough to read a bound such as
T: Display. - How to create a project with
cargo newand run it withcargo run.
Concurrency and parallelism
Concurrency means a program is structured as several tasks that make progress in overlapping time periods. Parallelism means several tasks are executing at the same instant on different CPU cores. The two are related but different:
- One core can run a concurrent program by switching quickly between tasks. Nothing runs in parallel, but the tasks still interleave.
- Several cores can run tasks in parallel only if the program has been split into tasks that can overlap.
People use threads for two main reasons. The first is throughput: splitting CPU-heavy work across cores. The second is responsiveness: letting one task wait on a slow thing, such as a socket or a disk, while another keeps working.
Operating system threads
A thread is an independent path of execution inside a process. Every thread has its own stack and its own program counter. All threads in a process share the same heap and the same global memory. That sharing makes threads cheap to communicate through, and it is also the source of nearly every threading bug.
Rust's std::thread uses a 1:1 model. Each std::thread::spawn call asks the operating system for a new native thread, and the OS scheduler decides when and on which core it runs. Early Rust versions had lightweight "green threads" scheduled by a runtime, but they were removed before Rust 1.0 so the language would not need a runtime.
The 1:1 model has practical consequences:
- Threads cost real resources. Each one gets its own stack, 2 MiB by default for spawned threads, and creating one takes system calls. Spawning a million is not realistic.
- The scheduler is outside your control. You cannot rely on one thread running before another unless you synchronize them.
- When the main thread returns from
main, the process exits and any threads still running are stopped. Waiting for threads is your job, and the next chapter covers it.
Here is a small program that starts three threads and reports how many cores the machine offers:
use std::thread;
fn main() {
let cores = thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1);
println!("parallelism available: {cores}");
let handles: Vec<_> = (0..3)
.map(|id| {
thread::spawn(move || {
println!("thread {id} running");
id * 10
})
})
.collect();
for handle in handles {
let result = handle.join().unwrap();
println!("result {result}");
}
}Run it several times. The thread N running lines can appear in a different order from one run to the next, because the OS schedules the threads. The result lines always appear in order, because the loop joins the handles in the order they were stored. This output order is the first thing to notice about threaded code. The program is correct, but its behavior is not fully determined by the source.
The next two chapters explain spawn, join, and move properly. Here you only need to see that each closure passed to spawn runs on its own thread.
The problem: data races
Threads share memory, so two of them can touch the same location at the same time. A data race occurs when all three of these conditions hold:
- Two or more threads access the same memory location.
- At least one of the accesses is a write.
- Nothing orders the accesses, such as a lock or an atomic operation.
Consider a counter that two threads increment. An increment looks like one step, but the hardware does it as three: read the value, add one, write it back. If both threads read 5 before either writes, both write 6, and one increment is lost. Worse, in C and C++ a data race is undefined behavior. The compiler is allowed to assume it never happens, so the program can misbehave in ways that no reading of the source explains.
Data races are hard to debug for a specific reason. They depend on timing, so a program can pass its tests a thousand times and fail in production. Adding a print statement can change the timing and hide the bug.
How Rust prevents data races
Rust does not detect data races at run time. It makes them impossible to express in safe code, using rules you already know from single-threaded Rust:
- A value has one owner at a time.
- You can have many shared references
&T, or one exclusive reference&mut T, but not both at once. - A reference cannot outlive the value it points to.
A data race needs shared access plus mutation. The aliasing rule says that mutation requires exclusive access, so safe Rust cannot give two threads a &mut to the same data. The same rules also cover the second family of threading bugs, use-after-free. If a thread borrowed a local variable and the function returned first, the thread would read freed stack memory. The compiler rejects that program with error E0373, "closure may outlive the current function", which is the reason spawned closures usually need move.
Rust adds one more mechanism for threads: two marker traits, Send and Sync. They record which types are safe to move to another thread and which are safe to share between threads. Library types such as Rc opt out, so you cannot send them across threads by accident. A later chapter covers these traits in detail. What matters now is that thread safety is part of the type system. The compiler checks it before the program runs, and checks it for every thread you spawn.
Rust's solution also leaves you a way to share data legitimately. The standard library provides types such as Mutex and mpsc::channel that are written, with a small amount of carefully reviewed unsafe code, to give you mutation under exclusive access or ownership transfer. You use them through a safe interface, and the compiler checks that you use them correctly.
What Rust does not guarantee
Rust's guarantee is narrow. It covers data races and memory safety, and it does not cover every concurrency bug. The table lists what the compiler does and does not catch in safe code.
| Problem | Prevented in safe Rust? | Notes |
|---|---|---|
| Data race on shared memory | Yes | Compile-time error |
| Use-after-free through a thread outliving a borrow | Yes | Compile-time error |
| Sending a non-thread-safe type such as `Rc` to another thread | Yes | Rejected through `Send` |
| Deadlock | No | Two threads each waiting for a lock the other holds |
| Race condition (logic error depending on timing) | No | For example, check-then-act across two separate lock acquisitions |
| Starvation or an unfair schedule | No | The OS scheduler decides |
| Memory leak | No | `Arc` cycles and `mem::forget` are safe |
| Panic inside a thread | No | Contained to that thread, reported to the joiner |
The distinction between a data race and a race condition matters in practice. Suppose you read a balance under a lock, release the lock, compute, then take the lock again and write. No data race exists, since every access was synchronized. The program still has a race condition, because another thread could change the balance between the two lock acquisitions. Rust does not warn you about this. You design around it by holding the lock for the whole operation, or by passing messages so one thread owns the data.
Two ways to coordinate threads
Safe Rust gives you two main styles for threads that must cooperate. Later chapters cover both.
- Message passing: threads do not share data. One thread sends a value through a channel, and ownership of the value moves to the receiver. The standard library provides
std::sync::mpscfor this. - Shared state: threads hold a handle to the same data and take turns using it, usually with
Arc<Mutex<T>>.
Neither is always better. The final chapter of this tutorial gives decision criteria, and the worker pool chapter combines both.
Summary
Threads are OS-scheduled paths of execution that share one heap. Shared memory plus unordered writes produces data races, and a data race is undefined behavior in languages that permit it. Rust uses ownership, borrowing, and the Send and Sync traits to reject data races at compile time. It does not prevent deadlocks, logic races, or leaks, so you still need to design thread interaction deliberately.
Exercise
A teammate says "Rust makes concurrency bugs impossible." Name one concurrency bug that safe Rust still allows, and explain why the compiler cannot catch it.
Show answer
Deadlock is one example: two threads each hold a mutex and wait for the other's. Another is a race condition, such as reading a value under a lock, releasing the lock, and writing a result computed from it later while another thread changed the value in between. The compiler checks memory access rules (aliasing, lifetimes, and thread-safety traits). Both bugs are correct with respect to those rules, and they only show up in the program's logic and its timing, which the type system does not model.
Exercise
In the three-thread example, why can the "thread N running" lines print in any order, while the "result N" lines always print in order 0, 1, 2?
Show answer
The OS scheduler decides when each spawned thread runs, so the order of the "running" lines is not fixed. The "result" lines are printed by the main thread, which calls join on the handles in the order they were stored in the Vec (thread 0, then 1, then 2). Each join waits for that specific thread, so the main thread's output order is fixed by the loop.
Exercise
State the three conditions that together define a data race.
Show answer
Two or more threads access the same memory location, at least one of the accesses is a write, and no synchronization (such as a lock or an atomic operation) orders the accesses.