April 2026
Intermediate
631 pages
16h 20m
English
In concurrent programming, controlling thread lifetimes and their interactions with data is critical for safety. Scoped threads in Rust offer a way to spawn threads that are guaranteed to terminate before a given scope ends, ensuring no dangling references. This feature allows for safer and more efficient use of data shared between threads.
Consider the code shown in Listing 14.32.
use std::thread;fn main() { let mut vec = vec![1, 2, 3]; thread::spawn(|| { println!("{:?}", vec); });}
Listing 14.32 A Simple Thread Trying to Print a Vector Defined in main
In this case, we have a vector defined in main, which is used inside a thread. As expected, this code throws an error, “closure may outlive the current function, but ...
Read now
Unlock full access