如何从函数流式传输 std::sync::mpsc::Receiver 的内容?
在所有结果可用之前,调用者应该能够收到结果。
理想情况下,我希望
fetch_all()
的返回类型独立于 std::sync::mpsc
,因此首选 impl Iterator<Item = &'a Result<FooResult<'a>, FooError<'a>>>
之类的类型。
下面的代码不起作用,因为
rx
是在堆栈上分配的,因此无法返回。
我想调用者可以将
tx
和 rx
传递到 fetch_all()
,有没有办法避免这种情况?
use std::sync::mpsc::{Receiver, Sender};
fn fetch(item: &'a str) -> Result<FooResult<'a>, FooError<'a>> {}
fn fetch_all(items: &'a [&'a str]) -> ??? { // What's the best return type?
let (tx, rx) = mpsc::channel();
let pool = ThreadPool::new(10);
for i in items {
let txx = tx.clone();
let item = i.to_owned();
pool.execute(move || {
let r = fetch(item)
txx.send(r).expect("Thread communication error");
});
pool.join();
std::mem::drop(sender);
rx.into_iter() // <- what should this be?
}
threadpool_scope
板条箱允许这样做:
use std::sync::mpsc;
use threadpool::ThreadPool;
use threadpool_scope::scope_with;
struct FooResult<'a>(&'a ());
struct FooError<'a>(&'a ());
fn fetch<'a>(item: &'a str) -> Result<FooResult<'a>, FooError<'a>> {
todo!()
}
fn fetch_all<'a>(
items: &'a [&'a str],
) -> impl Iterator<Item = Result<FooResult<'a>, FooError<'a>>> + 'a {
let (tx, rx) = mpsc::channel();
let pool = ThreadPool::new(10);
scope_with(&pool, |scope| {
for i in items {
let tx = tx.clone();
let item = i.to_owned();
scope.execute(move || {
let r = fetch(item);
tx.send(r).expect("Thread communication error");
});
}
});
drop(tx);
rx.into_iter()
}