闭包可能会在当前函数结束后继续存在。

huangapple go评论72阅读模式
英文:

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.
    });
}

huangapple
  • 本文由 发表于 2023年6月1日 23:40:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定