thread::spawn, JoinHandle::join, thread::scope
pub fn spawn<F, T>(f: F) -> JoinHandle<T>
where F: FnOnce() -> T + Send + 'static, T: Send + 'static
pub fn join(self) -> Result<T>
pub fn scope<'env, F, T>(f: F) -> TStart a thread, wait for it with join, or borrow local data with scope. Printing happens after join, so the output is not a race with the scheduler.
| Parameter | Description |
|---|---|
f | The closure to run on the new thread. spawn requires Send + 'static. scope allows borrowing values that outlive the scope call. |
Returns: spawn returns a JoinHandle. join returns Ok(T) if the thread finished, or Err with the panic payload if it panicked. scope returns the value of its closure after the scoped threads have finished.
Errors and panics
join Err— JoinHandle::join returns Err when the thread panicked. The example checks is_err and does not assert the payload display text.
- Do not use sleep as a substitute for join. The examples were compiled with rustc 1.90.0 and --edition=2024.
use std::thread;
fn main() {
let handle = thread::spawn(|| 2 + 3);
println!("{}", handle.join().unwrap());
std::panic::set_hook(Box::new(|_| {}));
let panicked = thread::spawn(|| panic!("boom")).join();
println!("{}", panicked.is_err());
let n = 10;
thread::scope(|s| {
let first = s.spawn(|| n + 1);
let second = s.spawn(|| n + 2);
println!("{} {}", first.join().unwrap(), second.join().unwrap());
});
}Expected output
5
true
11 12Related: Arc and Mutex