Creating threads

In Rust, things are similar to the C++ approach, where we have the std::thread module with the spawn() function. This function will receive a closure or a pointer to a function and execute it. It will return a handle to the thread, and we will be able to manage it from outside. Let's see how this works:

use std::thread;fn main() {    println!("Before the thread!");    let handle = thread::spawn(|| {        println!("Inside the thread!");    });    println!("After thread spawn!");    handle.join().expect("the thread panicked");    println!("After everything!");}

This will output something similar to this:

The Inside the thread! and After thread spawn! ...

Get Rust High Performance now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.