0

我正在尝试一次对几块字符串执行并行操作,但我发现借用检查器存在问题:

(对于上下文,来自 CSV 文件,identifiers是reqwest 并且是一次写入多次读取)Vec<String>clienttargetArc<String>

use futures::{stream, StreamExt};
use std::sync::Arc;

async fn nop(
    person_ids: &[String],
    target: &str,
    url: &str,
) -> String {
    let noop = format!("{} {}", target, url);
    let noop2 = person_ids.iter().for_each(|f| {f.as_str();});
    "Some text".into()
}

#[tokio::main]
async fn main() {
    let target = Arc::new(String::from("sometext"));
    let url = "http://example.com";
    let identifiers = vec!["foo".into(), "bar".into(), "baz".into(), "qux".into(), "quux".into(), "quuz".into(), "corge".into(), "grault".into(), "garply".into(), "waldo".into(), "fred".into(), "plugh".into(), "xyzzy".into()];

    let id_sets: Vec<&[String]> = identifiers.chunks(2).collect();

    let responses = stream::iter(id_sets)
        .map(|person_ids| {
            let target = target.clone();
            tokio::spawn( async move {
                let resptext = nop(person_ids, target.as_str(), url).await;
            })
        })
        .buffer_unordered(2);

    responses
        .for_each(|b| async { })
        .await;
}

操场:https ://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=e41c635e99e422fec8fc8a581c28c35e

给定块产生一个 Vec<&[String]>,编译器抱怨它的identifiers寿命不够长,因为它可能会在引用切片时超出范围。实际上这不会发生,因为有一个等待。有没有办法告诉编译器这是安全的,或者是否有另一种方法可以将块作为每个线程的一组拥有的字符串?

有一个类似的问题使用 into_owned() 作为解决方案,但是当我尝试这样做时,rustc 抱怨在 request_user 函数中编译时不知道切片大小。

编辑:还有一些其他问题:

  1. 是否有更直接的方式target在每个线程中使用而不需要 Arc?从创建的那一刻起,它就不需要修改,只需读取即可。如果没有,有没有办法将它从不需要 .as_str() 方法的 Arc 中拉出来?

  2. 您如何处理 tokio::spawn() 块中的多种错误类型?在实际使用中,我将在其中收到 quick_xml::Error 和 reqwest::Error 。它可以在没有 tokio spawn 的情况下正常工作。

4

2 回答 2

2

有没有办法告诉编译器这是安全的,或者是否有另一种方法可以将块作为每个线程的一组拥有的字符串?

您可以使用crate将 a 分块Vec<T>为 aVec<Vec<T>> 而无需克隆:itertools

use itertools::Itertools;

fn main() {
    let items = vec![
        String::from("foo"),
        String::from("bar"),
        String::from("baz"),
    ];
    
    let chunked_items: Vec<Vec<String>> = items
        .into_iter()
        .chunks(2)
        .into_iter()
        .map(|chunk| chunk.collect())
        .collect();
        
    for chunk in chunked_items {
        println!("{:?}", chunk);
    }
}
["foo", "bar"]
["baz"]

这是基于这里的答案。

于 2021-03-03T01:16:09.140 回答
1

您的问题是标识符是对切片的引用的向量。一旦你离开你的函数范围,它们就不一定会出现(这就是里面的异步移动会做的事情)。

您对当前问题的解决方案是将 转换Vec<&[String]>Vec<Vec<String>>类型。

实现这一目标的一种方法是:

    let id_sets: Vec<Vec<String>> = identifiers
        .chunks(2)
        .map(|x: &[String]| x.to_vec())
        .collect();
于 2021-03-02T22:35:35.187 回答