Threads and scoped threads
Quick answer
A thread is an independently scheduled execution path within a process. Threads can make progress concurrently and may run in parallel on separate CPU cores.
Choose an ownership boundary
thread::spawn returns a join handle and requires a closure and return value that satisfy Send and 'static. A scoped thread can borrow local data because thread::scope joins its outstanding threads before returning. Scheduling order is not guaranteed; join before reading a result. Creating threads has a cost, so parallelism is not automatically faster.
fn main() { let worker = std::thread::spawn(|| 6 * 7); println!("{}", worker.join().unwrap());}Expected stdout (not executed):
42The parent receives the returned value after completion.
fn main() { let data = [1, 2, 3, 4]; let total = std::thread::scope(|s| { let a = s.spawn(|| data[..2].iter().sum::<i32>()); let b = s.spawn(|| data[2..].iter().sum::<i32>()); a.join().unwrap() + b.join().unwrap() }); println!("{total}");}Expected stdout (not executed):
10Both workers borrow the array without cloning it.
Common mistake
Do not infer completion order from the order of spawn calls.
Try it yourself
Split a six-element array into three slices and sum the three partial results.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Threads and scoped threads — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A worker needs to borrow a local slice without cloning it. Which thread API suits this?
Threads and scoped threads — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let worker = std::thread::spawn(|| 6 * 7); println!("{}", worker.join().unwrap()); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Threads and scoped threads — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust fn main() { let data = [1, 2, 3, 4]; let total = std::thread::scope(|s| { let a = s.spawn(|| data[..2].iter().sum::<i32>()); let b = s.spawn(|| data[2..].iter().sum::<i32>()); a.join().unwrap() + b.join().unwrap() }); println!("{total}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.