以下代碼產生有趣的結果:
use std::thread;
fn main() {
let mut handles = Vec::new();
let mut v = vec![1, 2, 3, 4];
for x in v.chunks_exact_mut(2) {
let handle = thread::spawn(move || {
println!("Here's a vector: {:?}", x);
});
handles.push(handle);
}
for h in handles { h.join().unwrap(); }
}
error[E0597]: `v` does not live long enough
--> src/main.rs:7:14
|
7 | for x in v.chunks_exact_mut(2) {
| ^^^^^^^^^^^^^^^^^^^^^
| |
| borrowed value does not live long enough
| argument requires that `v` is borrowed for `'static`
...
16 | }
| - `v` dropped here while still borrowed
為什么“分塊”會v改變生命?如果沒有 'chunking' v,代碼將正確執行。那么為什么現在它會拋出錯誤?
uj5u.com熱心網友回復:
這里的問題是完全將生命周期與其他生命周期解耦,因為執行緒可能在已經完成thread::spawn時繼續運行。main
x是對 in 中的變數的參考main,并且不能保證其main壽命比執行緒長。
我認為您在這里真正想要的是一個執行緒幫助程式庫rayon,因為它們已經在內部解決了這些問題:
use rayon::prelude::*;
fn main() {
let mut v = vec![1, 2, 3, 4];
v.par_chunks_exact_mut(2).for_each(|x: &mut [i32]| {
let thread_id = std::thread::current().id();
println!("{:?}: Here's a vector: {:?}", thread_id, x);
});
}
ThreadId(5): Here's a vector: [1, 2]
ThreadId(2): Here's a vector: [3, 4]
uj5u.com熱心網友回復:
沒有“分塊” v,你就在迭代Vec<i32>。這個迭代器產生型別的專案i32,因此,沒有參考,沒有生命周期,滿足thread::spawn()(特別是'static要求)的要求。
chunks_exact_mut()但是,在切片上定義并提供迭代器 over &mut [T],因此它確實有一個參考。并且由于此參考參考v存在于 中main(),因此它不是'static也不起作用。
如果您將迭代&v而不是 ,則可以觀察到相同的問題v,因為該迭代器為您提供了&i32s ( playground ):
error[E0597]: `v` does not live long enough
--> src/main.rs:7:14
|
7 | for x in &v {
| ^^
| |
| borrowed value does not live long enough
| argument requires that `v` is borrowed for `'static`
...
16 | }
| - `v` dropped here while still borrowed
除此之外,我建議rayon按照@Finomnis 的建議使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491164.html
上一篇:多執行緒中基于函式輸入的鎖定
下一篇:關于執行緒間資料交換的問題
