问题描述
在下面的代码中,我必须将'static
的生存期添加到s
参数中,以消除此错误:
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");
}
我可以理解,编译器无法确保在函数run()
的末尾产生的线程全部完成;但是,实际上是这样的:线程都在函数结束之前无条件地连接在一起。因此,在这种情况下,我知道我不需要'static
的生命。
所以我想实现相同的功能,但没有'static
的要求:
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
}
我该怎么做?
解决方法
以下是使用crossbeam crate来解决此问题的方法:
meeting