Skip to content
systemcoding.dev
Concurrency

Spawn OS Threads in Rust with std::thread::spawn

Start OS threads in Rust with std::thread::spawn, move data in with move closures, read results from JoinHandle and handle a panicking thread safely.

6 min read
Summarize in AI
Flat illustration of parallel threads meeting at a mutex, with the Rust, Erlang and C++ logos.

Rust's standard library gives you real operating system threads, one per call to std::thread::spawn, and the compiler checks at build time that the data you hand to a thread cannot be freed or mutated unsafely behind its back. That check is the reason beginners hit their first Rust thread error within minutes: the closure "may outlive the current function". This post walks through spawning threads, moving data into them, collecting return values and reacting to a thread that panics, on Rust 1.90 (edition 2024). The C equivalent is covered in the pthread_create post.

One spawn, one join

std::thread::spawn takes a closure, starts a new OS thread running it, and returns a JoinHandle<T>, where T is the closure's return type:

src/main.rsrust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        println!("hello from the worker");
        42
    });

    let answer = handle.join().unwrap();
    println!("worker returned {answer}");
}
Text
hello from the worker
worker returned 42

join() blocks until the thread finishes and returns Result<T, Box<dyn Any + Send + 'static>>. The Ok side carries the closure's return value, here 42. The ordering of the two lines is fixed because the second println! runs after join returns.

If you drop a JoinHandle without joining, the thread keeps running, detached, and the process still ends when main returns, killing whatever is left. Unlike C++'s std::thread, dropping a handle never aborts the program.

Why the closure must be move

Most threads need data from the surrounding function. The first attempt looks natural and fails to compile:

rust
use std::thread;

fn main() {
    let name = String::from("Ada");
    let handle = thread::spawn(|| {
        println!("hello, {name}");
    });
    handle.join().unwrap();
}

The compiler stops with error E0373:

Text
error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function

spawn requires the closure to be 'static, meaning it must not borrow anything with a shorter lifetime. A spawned thread can outlive the function that created it, and a borrowed name would dangle once main's frame is gone. The fix is to transfer ownership with move:

src/main.rsrust
use std::thread;

fn main() {
    let name = String::from("Ada");
    let handle = thread::spawn(move || {
        println!("hello, {name}");
    });
    handle.join().unwrap();
}
Text
hello, Ada

After the move, name belongs to the thread and main can no longer use it. This is the rule the borrow checker enforces everywhere in Rust, applied to threads. The signature in the standard library documentation spells out the bounds: F: FnOnce() -> T + Send + 'static, T: Send + 'static.

To borrow instead of move, use scoped threads. Borrowing stack data with thread::scope shows how.

Send: what can cross a thread boundary

The Send bound means the closure's captured values and the return value must be safe to transfer to another thread. Most types are. A few deliberately are not, and the compiler rejects them:

rust
use std::rc::Rc;
use std::thread;

fn main() {
    let shared = Rc::new(5);
    let handle = thread::spawn(move || {
        println!("{shared}");
    });
    handle.join().unwrap();
}
Text
error[E0277]: `Rc<i32>` cannot be sent between threads safely

Rc updates its reference count without atomic operations, so two threads touching clones of one Rc would corrupt the count. The type that does the same job safely is Arc, which uses atomic increments. Replace Rc::new(5) with std::sync::Arc::new(5) and the program compiles.

Many threads, many results

Spawn in a loop, keep the handles, then join each one in order:

src/main.rsrust
use std::thread;

fn main() {
    let mut handles = Vec::new();
    for id in 0..4u64 {
        handles.push(thread::spawn(move || {
            let square = (id + 1) * (id + 1);
            (id, square)
        }));
    }

    for handle in handles {
        let (id, square) = handle.join().unwrap();
        println!("worker {id} computed {square}");
    }
}
Text
worker 0 computed 1
worker 1 computed 4
worker 2 computed 9
worker 3 computed 16

The threads may finish in any order, but the loop joins them in spawn order, so the printed order is stable. Each closure captures its own copy of id through move, which avoids the shared-loop-variable bug that plagues the C version. Returning a tuple is the idiomatic way to send a result back: there is no output parameter and no shared variable.

When a thread panics

A panic in a spawned thread does not take the process down. It unwinds that thread's stack, and join() reports it as Err:

src/main.rsrust
use std::thread;

fn main() {
    let handle = thread::spawn(|| {
        let data = vec![1, 2, 3];
        data[10]
    });

    match handle.join() {
        Ok(value) => println!("got {value}"),
        Err(_) => println!("worker panicked"),
    }
}
Text
thread '<unnamed>' panicked at src/main.rs:5:9:
index out of bounds: the len is 3 but the index is 10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
worker panicked

The panic message goes to standard error, and the Err arm runs in the main thread. The Err value is a Box<dyn Any + Send> holding the panic payload; for panic!("text") it downcasts to &'static str or String. This behavior depends on the default panic = "unwind" setting. With panic = "abort" in the Cargo profile, any panic ends the whole process.

Calling .unwrap() on a join result, as the earlier examples do, turns a worker panic into a main-thread panic. That is often the right default for a short program. A server that must keep serving should match on the result instead.

Naming threads and setting a stack size

thread::spawn is a shortcut for thread::Builder::new().spawn(...). Using the builder explicitly lets you name the thread, which shows up in panic messages and debuggers, and set its stack size:

src/main.rsrust
use std::thread;

fn main() -> std::io::Result<()> {
    let handle = thread::Builder::new()
        .name("log-writer".to_string())
        .stack_size(512 * 1024)
        .spawn(|| {
            let current = thread::current();
            println!("running as {}", current.name().unwrap_or("?"));
        })?;

    handle.join().unwrap();
    Ok(())
}
Text
running as log-writer

The builder's spawn returns io::Result<JoinHandle<T>>, because creating an OS thread can fail when resources run out. The plain thread::spawn panics in that case, which is a reason to use the builder in code that spawns threads on behalf of users. The default stack size for a spawned thread is 2 MiB, and stack_size takes bytes. On Linux, Rust passes the thread name to the operating system, so tools such as top -H and gdb show it, truncated to 15 bytes by the kernel's limit.

Platform notes

Each spawn creates a native thread. On Linux that is a pthread, built on clone, so every cost discussed for C threads applies: a stack mapping, a kernel task and a scheduler entry. If you need thousands of concurrent tasks, an async runtime or a thread pool is the usual answer, and spawning one OS thread per request is not.

Channels, scoped threads or shared state

A closure that must give its result back has three honest options. For a single value, return it from the closure and read it with join(), as shown above. For a stream of values, a channel from std::sync::mpsc moves them one at a time and lets the receiver loop until the sender is dropped. For borrowing data that outlives the threads, thread::scope removes the 'static requirement and the need for Arc.

Reach for Arc<Mutex<T>> last. It works, and it is the shape that most tutorials show first, but it turns a data flow problem into a locking problem. If you find yourself cloning an Arc into every closure, ask whether each thread could own its piece of the data and send back a result instead. The compiler pushes you in this direction deliberately: the Send and 'static bounds on spawn make sharing awkward, so that ownership transfer is the easy path.

A related detail concerns the process exit. When main returns, Rust ends the process and the remaining threads are stopped without running their destructors. A spawned thread that is still writing a file at that moment can leave it truncated. Keep the JoinHandle and join it before returning from main whenever the thread's work matters.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.