如何解决线程:如何删除静态寿命要求
在下面的代码中,我必须将'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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。