英文:
Closure might outlive current function even though it is joined
问题
fn main() {
let foo = 5;
std::thread::spawn(|| { // 闭包可能会超出当前函数的生命周期,但它借用了当前函数拥有的 `foo`
println!("{}", foo);
})
.join()
.unwrap();
}
将值移动不是一个选项,因为必须创建多个线程。
我的代码情况有点复杂,但我仍然需要线程,所以我最终将 Arc
移入线程,而不仅仅是引用。
这是项目中的代码行链接,但您不必阅读它: https://github.com/Antosser/web-crawler/blob/5d23ffa7ed64c772080c7be08a26bda575028c7c/src/main.rs#L291
英文:
fn main() {
let foo = 5;
std::thread::spawn(|| { // closure may outlive the current function, but it borrows `foo`, which is owned by the current function
println!("{}", foo);
})
.join()
.unwrap();
}
Moving the value is not an option since it have to make multiple threads
The situation in my code is a bit more complicated, but I still need threads and I ended up moving and Arc into it instead of just a reference
Here is a link to the line in the project, but you don't have to read it: https://github.com/Antosser/web-crawler/blob/5d23ffa7ed64c772080c7be08a26bda575028c7c/src/main.rs#L291
答案1
得分: 1
编译器不知道它们已连接。它不会应用任何特殊分析来查看线程是否已连接。
然而,如果你连接你的线程,你可以使用作用域线程来访问变量:
fn main() {
let foo = 5;
std::thread::scope(|s| {
s.spawn(|| {
println!("{}", foo);
});
// 线程在此隐式连接。
});
}
英文:
The compiler does not know it is joined. It does not apply any special analysis to see if threads are joined.
However, if you join your threads, you can use scoped threads to access variables:
fn main() {
let foo = 5;
std::thread::scope(|s| {
s.spawn(|| {
println!("{}", foo);
});
// Thread implicitly joined here.
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论