How do you use thread::spawn in Rust?
Answer
std::thread::spawn creates a new OS thread. It takes a closure and runs it in the new thread: let handle = thread::spawn(|| { println!("from thread"); });. The closure must be 'static (contain no non-static references) and implement Send (safe to send across threads). Use the move keyword to transfer ownership of variables into the closure: thread::spawn(move || { use_my_data(data); }). The function returns a JoinHandle<T> where T is the closure's return type. Call handle.join() (returns Result) to wait for the thread to finish and get its return value. If threads need to share data, use Arc<Mutex<T>> — never raw shared mutable state.
Previous
What are Rust channels for message passing?
Next
How does unit testing and integration testing work in Rust?
More Rust Questions
View all →- Intermediate How does error handling with the ? operator work in Rust?
- Intermediate What are the thiserror and anyhow crates for error handling?
- Intermediate What are trait objects (dyn Trait) in Rust?
- Intermediate What are generics in Rust and how do where clauses work?
- Intermediate What are Rust smart pointers?