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

问题描述 投票:0回答:1

我有一个Vec<u8>,我想多次进行一些操作。我会用Arc。这是MVCE:

use futures::executor::{block_on, ThreadPool};
use futures::task::SpawnExt;
use std::pin::*;
use std::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};
use futures::task::SpawnExt;
use std::pin::*;
use std::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);
    }
}

自然会产生错误'argument requires that v1 is borrowed for 'static

我知道Pin应该将vec数据固定到特定点,这样所有调用都可以引用相同的数据。什么是使用Pin的正确方法,以便我可以将引用传递给foo()

包装:期货0.3Rust 1.39稳定

rust async-await
1个回答
0
投票

缺少move

更改

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

 let handle = pool
        .spawn_with_handle(**async move** {
            foo(&*v1);
        })
        .unwrap();
© www.soinside.com 2019 - 2024. All rights reserved.