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
- Scoped threads may hold references to the stack.
- The scope joins every thread before it returns.
- No
Arcis needed for read-only sharing.
Keywords and builtins used here
fni32letmainuse
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.
Step 3 of 3 in Threads, step 3 of 15 in Concurrency & async.