以下代码产生了有趣的结果:
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会改变生命周期?如果没有“分块”v,代码将正确执行。那么为什么现在它会抛出一个错误呢?
发布于 2022-06-10 10:52:36
这里的问题是,thread::spawn将整个生命周期与其他线程完全解耦,因为线程可能会在main已经完成时继续运行。
x是对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]发布于 2022-06-11 23:35:35
如果没有“分块”v,则在Vec<i32>上迭代。这个迭代器生成类型为i32的项,因此,没有引用,没有生命周期,满足了thread::spawn() (特别是'static需求)的要求。
chunks_exact_mut(),然而,定义在片上。和提供迭代器的&mut [T],所以它确实有一个引用。由于这个引用引用的是v,它存在于main()中,所以它不是'static,也不工作。
如果要在&v上而不是v上迭代,您可以观察到同样的问题,因为迭代器给出了&i32s (游乐场):
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除此之外,我建议使用@Finomnis建议的rayon。
https://stackoverflow.com/questions/72572801
复制相似问题