I dont understand this lifetime error : spawining threads inside a struct function

I dont understand this lifetime error : spawining threads inside a struct function

不多解释。我不明白编译器错误消息甚至将生命周期指定为 1 and 2 是什么。

目前为止我检查过的所有帖子都说使用 crossbeam 作为 scopped threads,但这根本没有解决我的问题,我认为我什至不明白这里的更精细的问题。

感谢任何帮助。

use crossbeam_utils::thread;

struct TestStruct {
    s: f64,
}

impl TestStruct {
    fn new() -> Self {
        Self {
            s: -1.,
        }
    }
    fn fubar(&'static self) -> f64 {
        let thread_return_value = thread::scope(|scope|
            // lifetime may not live long enough
            // returning this value requires that `'1` must outlive `'2`
            // Question: what are the two lifetimes even of? I am probably just
            // a noob here.
            scope.spawn(move |_| { // same error with or without move
                // I have found that it doesnt matter what I put in this scope,
                // but the following is the closest to what I have in my actual
                // code.
                let mut psum = 0.;
                for _ in 0..10 { psum += self.s; }
                psum
            })
        ).unwrap();
        // do anything with thread_return_value

        return 0.; // just so its explicitly not the problem here, return 0.
    }
}


fn main() {
    let test_item = TestStruct::new();
    // rustcE0597
    let stored_value = test_item.fubar();
    println!("{}", &stored_value);
    return;
}

在标记为正确答案后编辑,工作最少的示例:

#![feature(let_chains)]
use crossbeam_utils::thread;


struct TestStruct {
    s: f64,
}

impl TestStruct {
    fn new() -> Self {
        Self {
            s: -1.,
        }
    }

    fn fubar(&self) -> f64 {
        let thread_return_value = thread::scope(|scope| {
            let th = scope.spawn(move |_| {
                let mut psum = 0.;
                for _ in 0..10 { psum += self.s; }
                psum
            });
            let psum = th.join().unwrap();
            psum
        }
        ).unwrap();
        return thread_return_value;
    }
}


fn main() {
    let test_item = TestStruct::new();
    // rustcE0597
    let stored_value = test_item.fubar();
    println!("{}", &stored_value);
    return;
}

代码中最明显的问题是 &'static self 生命周期。如果这样做,您将只能使用此类型的静态(即全局)值调用此函数。所以只需删除 'static 并写入 &self.

那么真正的问题是因为您正在尝试 return 来自 crossbeam::scoped 的作用域线程句柄,return 由 scope.spawn() 编辑的值,那就是不允许。这就是为什么它们被称为 scoped threads 的原因:它们被限制在封闭的范围内。

请记住,在 Rust 中,当一个块结束时没有 ; 最后一个表达式的值被 return 编辑为块本身的值。

您可能想要 return psum。如果是这样,您需要等待句柄完成:

    fn fubar(& self) -> f64 {
        let thread_return_value = thread::scope(|scope| {
            let th = scope.spawn(move |_| {
                let mut psum = 0.;
                for _ in 0..10 { psum += self.s; }
                psum
            }); // <--- here, add a ;
            let psum = th.join().unwrap(); //get the inner result
            psum //forward it to the outer scope
        }).unwrap();
        return 0.;
    }