bhylu.com

Advertisements

Rust Scoped Threads

Borrow local input only while a scope guarantees worker completion.

How it works

Scoped threads can borrow data from the surrounding scope because the scope ensures they finish before that scope returns. This can avoid cloning a collection purely to satisfy an ordinary spawned thread’s lifetime requirement. Borrowing rules still apply: shared reads and exclusive writes need appropriate separation. Scoped lifetime guarantees do not make a logically incorrect partition correct.

Run the code

Reviewed with Rust 1.97.0, edition 2024, using the standard library only. Save the complete download as lesson-name.rs in a separate learning folder, compile with rustc --edition=2024 lesson-name.rs and run the resulting program (lesson-name.exe on Windows). Use the actual lesson filename. The final project includes complete Cargo package files; run cargo test --offline and cargo run --offline from that separate package folder. There is no Rust browser runner; PHP, Apache and MySQL are not needed.

This complete example was executed in the stated local review environment.

Download complete source

Example

scoped-threads.rs

fn main() {
    let counts = [3_u32,5,8];
    let total = std::thread::scope(|scope| {
        let worker = scope.spawn(|| counts.iter().sum::<u32>());
        worker.join().expect("fixture worker")
    });
    assert_eq!(total, 16);
    assert_eq!(counts[0], 3);
    println!("Scoped worker borrowed counts; total 16");
}

Expected result

Scoped worker borrowed counts; total 16

The worker reads through a shared borrow and is joined while the counts array is still owned by the caller. The original remains available afterward. A scope can simplify lifetime reasoning, but failures, panics and task granularity still deserve review before parallelising an actual workload.

Primary technical reference: Rust documentation.