Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Rust Dictionary

  1. Home
  2. Rust Dictionary
  3. std::thread::spawn() / join()

std::thread::spawn() / join()

Use std::thread::spawn() to create a new thread, then call join() on the returned JoinHandle to wait for the thread to finish. Rust's thread model is designed to be thread-safe, preventing data races at compile time.

Syntax

use std::thread;

// Spawn a new thread.
let handle = thread::spawn(|| {
    // Code to run in the thread
});

// Wait for the thread to finish.
handle.join().unwrap();

// Use a move closure to pass external variables into the thread.
let data = value;
let handle = thread::spawn(move || {
    // data is moved into and owned by the thread.
    println!("{:?}", data);
});
handle.join().unwrap();

Methods

Method / FunctionDescription
thread::spawn(f)Runs closure f on a new OS thread and returns a JoinHandle.
handle.join()Waits for the thread to finish and returns a Result.
thread::sleep(d)Puts the current thread to sleep for the specified duration.
thread::current()Returns information about the current thread as a Thread value.
thread::Builder::new()Lets you configure a thread name and stack size before spawning.

Sample Code

use std::thread;
use std::time::Duration;

fn main() {
    // Spawn multiple threads and collect their results.
    let handles: Vec<_> = (0..5).map(|i| {
        thread::spawn(move || {
            // i is moved into the thread via the move closure.
            thread::sleep(Duration::from_millis(10 * i));
            format!("thread {} done", i)
        })
    }).collect();

    // Collect the return value from each thread.
    for handle in handles {
        let result = handle.join().unwrap();
        println!("{}", result);
    }

    // Spawn a named thread.
    let builder = thread::Builder::new().name("worker".to_string());
    let handle = builder.spawn(|| {
        println!("thread name: {:?}", thread::current().name());
    }).unwrap();
    handle.join().unwrap();
}

Notes

Rust verifies at compile time that any data passed to a thread implements the Send trait. This guarantees that data races cannot occur at runtime.

When passing external variables to a thread, you must transfer ownership rather than pass a reference. The standard pattern is to use the move keyword on the closure to move values into the thread.

If the main thread exits without calling join(), any spawned threads are forcibly terminated. Always call join() when you need to ensure a thread's work completes.

If you find any errors or copyright issues, please .