Spawning Threads
Run code concurrently.
What Is a Thread?
A thread lets your program run code concurrently. The operating system can schedule multiple threads, so work can overlap.
Rust's standard library exposes threads through the std::thread module. These are native OS threads, sometimes called 1:1 threads.
In this lesson you will learn to start new threads and control how they run.
Spawning with thread::spawn
You create a new thread by calling thread::spawn and passing it a closure. The closure holds the code the new thread will run.
The call returns immediately with a JoinHandle, while the spawned thread runs in the background.
use std::thread;
fn main() {
thread::spawn(|| {
println!("hello from a thread");
});
println!("hello from main");
}