Move Ownership Into Threads With Spawn And Join

Move owned data into thread::spawn closures, then recover each result through join, which also surfaces worker panics as Err instead of crashing the caller.

RustResilience

Code

rustsnippet
34 lines
use std::thread;

#[derive(Debug)]
struct Chunk {
    label: String,
    values: Vec<i64>,
}

fn main() {
    let chunks = vec![
        Chunk { label: "alpha".into(), values: vec![3, 1, 4] },
        Chunk { label: "beta".into(), values: vec![1, 5, 9] },
        Chunk { label: "gamma".into(), values: vec![2, 6, 5] },
    ];

    // spawn 要求闭包 'static:move 闭包把每个 Chunk 的所有权整体移交线程
    let handles: Vec<_> = chunks
        .into_iter()
        .map(|chunk| {
            thread::spawn(move || {
                let sum: i64 = chunk.values.iter().sum();
                format!("{} sums to {}", chunk.label, sum)
            })
        })
        .collect();

    // join 把闭包返回值的所有权交回主线程;线程 panic 时返回 Err
    for handle in handles {
        match handle.join() {
            Ok(message) => println!("{message}"),
            Err(_) => println!("worker panicked"),
        }
    }
}

Inside the snippet

Move Ownership Into Threads With Spawn And Join is built around the function main.

Repetition is confined to for handle in handles — the rest of the file is straight-line. Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.

Using it

The demo output is labeled (worker panicked), so every printed line maps back to its originating operation.

Key statements

let sum: i64 = chunk.values.iter().sum();
match handle.join() {
Ok(message) => println!("{message}"),
Err(_) => println!("worker panicked"),
}

Interactive Tools for This Topic

FAQ

What does Move Ownership Into Threads With Spawn And Join print when run?
Running the file directly is enough — expect labeled output lines such as `worker panicked`.