In the code below, I had to add the 'static
lifetime to the s
parameter, in order to get rid of this error:
error[E0621]: explicit lifetime required in the type of `s`
--> src/main.rs:4:14
|
3 | fn run(s: &str) {
| ---- help: add explicit lifetime `'static` to the type of `s`: `&'static str`
4 | let h1 = thread::spawn(move || {
| ^^^^^^^^^^^^^ lifetime `'static` required
use std::thread;
fn run(s: &'static str) {
let h1 = thread::spawn(move || {
println!("{} from thread 1", s);
});
let h2 = thread::spawn(move || {
println!("{} from thread 2", s);
});
h1.join().unwrap();
h2.join().unwrap();
}
fn main() {
run("hi");
}
I can understand that the compiler is unable to ensure that the spawned threads are all finished at the end of the function run()
; however in pratice, this is the case: the threads are both joined before the function ends, without condition. So in this case, I know that I don't need a 'static
lifetime.
So what I would like is to implement the same function, but without the 'static
requirement:
fn run(s: &str) {
// Spawn some threads which have read access to the variable 's'
// Join all the threads at the end of the function
}
How can I do that?