Rust

Threads with thread::spawn + join

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Native OS threads with `std::thread::spawn`. The returned `JoinHandle` lets you wait for the thread and get its return value. Use `move` to transfer ownership of captured variables.
Rust
Raw
use std::thread;

fn main() {
    let data = vec![1u64, 2, 3, 4, 5];

    // Spawn — must move ownership of `data` into the thread
    let handle = thread::spawn(move || {
        data.iter().sum::<u64>()
    });

    // Caller does other work concurrently…
    println!("main thread doing other stuff");

    // Wait + collect the return value
    let total = handle.join().unwrap();
    println!("sum = {total}");

    // Pool of N workers — collect handles, then join them all
    let handles: Vec<_> = (0..4).map(|i| {
        thread::spawn(move || {
            println!("worker {i}");
            i * 100
        })
    }).collect();
    let results: Vec<i32> = handles.into_iter().map(|h| h.join().unwrap()).collect();
    println!("{results:?}");
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.