gpt4 book ai didi

rust - 如何使用 Pin 而不是 Arc 通过引用异步 block 来传递 Vec

转载 作者:行者123 更新时间:2023-11-29 08:30:40 25 4
gpt4 key购买 nike

我想对 Vec<u8> 进行操作多次使用 Arc :

use futures::{
executor::{block_on, ThreadPool},
task::SpawnExt,
}; // 0.3.4
use std::{pin::*, sync::Arc};

fn foo(b: Arc<Vec<u8>>) {
println!("{:?}", b);
}

#[test]
fn pin_test() {
let v = Arc::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let mut pool = ThreadPool::new().unwrap();
for _ in 0..10 {
let v1 = v.clone();
let handle = pool
.spawn_with_handle(async {
foo(v1);
})
.unwrap();
block_on(handle);
}
}

我期待能够 Pin Vec<u8>相反

use futures::{
executor::{block_on, ThreadPool},
task::SpawnExt,
}; // 0.3.4
use std::{pin::*, sync::Arc};

fn foo(b: &[u8]) {
println!("{:?}", b);
}

#[test]
fn pin_test() {
let v = Pin::new(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
let mut pool = ThreadPool::new().unwrap();
for _ in 0..10 {
let v1 = v.clone();
let handle = pool
.spawn_with_handle(async {
foo(&*v1);
})
.unwrap();
block_on(handle);
}
}

这给出了错误:

error[E0597]: `v1` does not live long enough
--> src/lib.rs:19:23
|
18 | .spawn_with_handle(async {
| ________________________________-_____-
| |________________________________|
| ||
19 | || foo(&*v1);
| || ^^ borrowed value does not live long enough
20 | || })
| || -
| ||_____________|
| |______________value captured here by generator
| argument requires that `v1` is borrowed for `'static`
...
23 | }
| - `v1` dropped here while still borrowed

我明白 Pin应该固定 Vec数据到特定点,这样所有调用都可以引用相同的数据。怎样才是正确的使用方法Pin这样我就可以传递对 foo() 的引用?

我正在使用 Rust 1.39。

最佳答案

你错过了一个move

改变

let handle = pool
.spawn_with_handle(async {
foo(&*v1);
})
.unwrap();

let handle = pool
.spawn_with_handle(async move {
// ^^^^
foo(&*v1);
})
.unwrap();

关于rust - 如何使用 Pin 而不是 Arc 通过引用异步 block 来传递 Vec<u8> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58754442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com