O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Threads

The standard library contains the spawn function for launching new threads:

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

Here's what the function declaration says:

  • spawn takes a parameter f, which implements the FnOnce trait. In other words, f is a closure.
  • The f closure must implement the Send trait, which means that all its parameters must implement the Send trait.
  • The T return type from the closure must also implement the Send trait.
  • spawn returns JoinHandle with a value of the T type enclosed.

Send is a marker trait. This means that it does not implement any methods; it is just used as a mark that says that the value is safe to be sent between threads: most types, and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required