不多解釋。我不明白1 and
編譯器錯誤訊息指定的生命周期為 2 是什么。
到目前為止我檢查過的所有帖子都只是說使用橫梁來處理范圍內的執行緒,但這根本沒有解決我的問題,我認為我什至不理解這里更精細的問題。
任何幫助表示贊賞。
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;
}
uj5u.com熱心網友回復:
代碼中最明顯的問題是&'static self
生命周期。如果這樣做,您將只能使用此型別的靜態(即全域)值呼叫此函式。所以只需洗掉它'static
并寫入&self
.
那么真正的問題是因為您試圖從 中回傳您的作用域執行緒句柄,crossbeam::scoped
回傳的值是scope.spawn()
,這是不允許的。這就是為什么它們被稱為作用域執行緒:它們僅限于封閉作用域。
請記住,在 Rust 中,當一個塊結束時沒有;
最后一個運算式的值作為塊本身的值回傳。
您可能想要回傳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.;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/470128.html
上一篇:至少一個完成后如何啟動執行緒