Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ CONCURRENCY WITH A CONTRACT
BUILD NOTE 41 / 53

Let work run independently.

Transfer ownership into a thread and join its result.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

std::thread::spawn runs a closure on another operating-system thread. Spawned closures generally need owned or static data because the new thread may outlive the caller’s current stack frame. A move closure can transfer a vector into the thread. join waits for termination and returns a Result because the thread may panic. Thread scheduling is nondeterministic, so do not depend on print ordering. For borrowed work that must finish before a scope exits, scoped threads provide a useful alternative.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/threads/src/main.rs
use std::thread;
fn main() {
    let values = vec![2, 4, 6];
    let worker = thread::spawn(move || values.into_iter().sum::<i32>());
    let total = worker.join().expect("worker completed");
    println!("total={total}");
}
↳ EXPECTED OUTPUT
total=12
  1. 1

    move transfers the vector into the closure.

  2. 2

    The worker owns the values it consumes.

  3. 3

    join returns the final sum and synchronizes completion.

From the extracted rust-workbench folder
cargo run -p lesson_threads

03 Mind the boundary

04 Your next build

A SMALL MISSION

Use thread::scope to sum two borrowed halves, then combine the results.

Reveal one possible solution +
solutions/threads/src/main.rs
use std::thread;
fn main() {
    let values = [1, 2, 3, 4];
    let total = thread::scope(|scope| {
        let a = scope.spawn(|| values[..2].iter().sum::<i32>());
        let b = scope.spawn(|| values[2..].iter().sum::<i32>());
        a.join().unwrap() + b.join().unwrap()
    });
    assert_eq!(total, 10);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does dropping a JoinHandle cancel the thread?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.