Concurrency in Rust
Rust's concurrency primitives rely on native OS threads. It provides threading APIs in the std::thread
module in the standard library. In this section, we'll start with the basics on how to create threads to perform tasks concurrently. In subsequent sections, we'll explore how threads can share data with each other.
Thread basics
As we said, every program starts with a main thread. To create an independent execution point from anywhere in the program, the main thread can spawn a new thread, which becomes its child thread. Child threads can further spawn their own threads. Let's look at a concurrent program in Rust that uses threads in the simplest way possible:
// thread_basics.rs use std::thread; fn main() { thread::spawn(|| { println!("Thread!"); "Much concurrent, such wow!".to_string() }); print!("Hello "); }
In main
, we call the spawn
function from the thread
module which takes a no parameter closure as an argument. Within this closure...