# Function std::thread::spawn 1.0.0 [−] [src]

    pub fn spawn<F, T>(f: F) -> JoinHandle<T> where
        F: FnOnce() -> T,
        F: Send + 'static,
        T: Send + 'static,

Spawns a new thread, returning a `JoinHandle` for it.

The join handle will implicitly detach the child thread upon being dropped. In this case, the child thread may outlive the parent (unless the parent thread is the main thread; the whole process is terminated when the main thread finishes). Additionally, the join handle provides a `join` method that can be used to join the child thread. If the child thread panics, `join` will return an `Err` containing the argument given to `panic`.

This will create a thread using default parameters of `Builder`, if you want to specify the stack size or the name of the thread, use this API instead.

# Panics

Panics if the OS fails to create a thread; use `Builder::spawn` to recover from such errors.

# Examples

Creating a thread.

    use std::thread;

    let handler = thread::spawn(|| {
        // thread code
    });

    handler.join().unwrap();Run

As mentioned in the module documentation, threads are usually made to communicate using `channels`, here is how it usually looks.

This example also shows how to use `move`, in order to give ownership of values to a thread.

    use std::thread;
    use std::sync::mpsc::channel;

    let (tx, rx) = channel();

    let sender = thread::spawn(move || {
        let _ = tx.send("Hello, thread".to_owned());
    });

    let receiver = thread::spawn(move || {
        println!("{}", rx.recv().unwrap());
    });

    let _ = sender.join();
    let _ = receiver.join();Run

A thread can also return a value through its `JoinHandle`, you can use this to make asynchronous computations (futures might be more appropriate though).

    use std::thread;

    let computation = thread::spawn(|| {
        // Some expensive computation.
        42
    });

    let result = computation.join().unwrap();
    println!("{}", result);Run

# Help

## Keyboard Shortcuts

?
  Show this help dialog
S
  Focus the search field
⇤
  Move up in search results
⇥
  Move down in search results
⏎
  Go to active search result
+
  Collapse/expand all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)