I'm studying concurrency now. I wrote the below code to understand it, but an error occurs about lifetime. I do not understand this error. Rust Playground
use std::thread;
fn main() {
let mut handles = Vec::new();
for x in 0..10 {
handles.push(thread::spawn(|| {
println!("{}", x);
}));
}
for handle in handles {
handle.join();
}
}
An error message is
closure may outlive the current function, but it borrows `x`, which is owned by the current function
In this message, what function "the current function" means? If this means fn main(), closure must be in it, so I cannot understand this error message.
thread::spawn allows that the spawned thread outlives the caller. For this reason, it requires that the passed closure has 'static as lifetime. The closure here however is borrowing the variable x, which gives it a lifetime of at most the body of the loop, as the next iteration drops the current x. The solution is to force x to be moved into the closure using move || { /* ... */ }.
std::thread::spawn always allows the spawned thread to outlive the caller. The crossbeam and rayon crates provide so called "scoped" threads. Those can borrow values from the caller.