Spawning threads in Rust
spawn starts a thread and hands back a handle; join waits and collects its value.
use std::thread;
fn main() {
let worker = thread::spawn(|| {
let total: u64 = (1..=1_000).sum();
total
});
println!("main keeps working");
match worker.join() {
Ok(total) => println!("worker said {total}"),
Err(_) => println!("worker panicked"),
}
}
How it works
- The closure runs on the new thread immediately.
joinblocks until that thread finishes.- The closure's return value comes back through
join.
Keywords and builtins used here
ErrOkfnletmainmatchu64use
The run, in numbers
- Lines
- 15
- Characters to type
- 252
- Tokens
- 81
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 49 seconds.
Step 1 of 3 in Threads, step 1 of 15 in Concurrency & async.