typestar

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

  1. The closure runs on the new thread immediately.
  2. join blocks until that thread finishes.
  3. The closure's return value comes back through join.

Keywords and builtins used here

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.

Type this snippet

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

Next →