A thread of execution is a sequence of CPU instructions intended to run serially within a process. The operating system schedules threads, allowing a program to work on multiple tasks concurrently. Threads in the same process share an address space; separate processes have protected, independent memory. section 10.2 section 10.5 section 10.5.3
Concurrency does not require multiple CPU cores. On one core, a thread waiting for memory or input/output can be blocked while another runs. Parallelism means using multiple physical cores at once. section 10.0
Listing 10.3 Creating two subthreads to perform work on our behalf
1 use std::{thread, time};
2
3 fn main() {
4 let start = time::Instant::now();
5
6 let handler_1 = thread::spawn(move || {
7 let pause = time::Duration::from_millis(300);
8 thread::sleep(pause.clone());
9 });
10
11 let handler_2 = thread::spawn(move || {
12 let pause = time::Duration::from_millis(300);
13 thread::sleep(pause.clone());
14 });
15
16 handler_1.join().unwrap();
17 handler_2.join().unwrap();
18
19 let finish = time::Instant::now();
20
21 println!("{:?}", finish.duration_since(start));
22 }
This Rust program spawns two threads with closures. Each sleeps for 300 milliseconds; the main thread joins both before reporting the elapsed time. section 10.2.3
The operating system decides when threads run, so their execution order is not guaranteed. If multiple threads try to write the same data without appropriate coordination, the result could depend on scheduling. Rust rejects the illustrated attempt to give both spawned threads and the main thread write access to the same variable. section 1.6.1
Listing 1.4 Example of Rust preventing a race condition
use std::thread; #1
fn main() {
let mut data = 100;
thread::spawn(|| { data = 500; }); #2
thread::spawn(|| { data = 1000; }); #2
println!("{}", data);
}
Both spawned closures attempt to change the same variable. The example does not compile, demonstrating Rust's protection against this attempted race. section 1.6.1
A few threads need not impose a large cost: one comparison found a difference of 0.24 milliseconds, though it was not a robust benchmark. Many threads are another matter. Each needs memory, scheduling takes work, and switching threads can invalidate caches. In one experiment, CPU-intensive work degraded quickly once the thread count exceeded the six physical cores. section 10.2.3 section 10.2.4
Threads are the smallest unit of isolation the operating system schedules. Smaller concurrent tasks, such as coroutines, are managed inside a process and are invisible to the OS. If a thread blocks, coroutines running on that thread cannot progress until it resumes. section 10.5.1 section 10.5











