typestar

Scoped threads in Rust

thread::scope lets threads borrow local data, because they cannot outlive the scope.

use std::thread;

fn main() {
    let scores = vec![91, 104, 87, 96];

    thread::scope(|s| {
        s.spawn(|| {
            let total: i32 = scores.iter().sum();
            println!("sum {total}");
        });
        s.spawn(|| {
            println!("max {:?}", scores.iter().max());
        });
    });

    println!("still ours: {:?}", scores);
}

How it works

  1. Scoped threads may hold references to the stack.
  2. The scope joins every thread before it returns.
  3. No Arc is needed for read-only sharing.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
271
Tokens
104
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 62 seconds.

Type this snippet

Step 3 of 3 in Threads, step 3 of 15 in Concurrency & async.

← Previous Next →