如何从scoped_threadpool线程返回错误?

6

我有一些代码,使用了scoped_threadpool,类似于这样:

extern crate scoped_threadpool;

use scoped_threadpool::Pool;
use std::error::Error;

fn main() {
    inner_main().unwrap();
}

fn inner_main() -> Result<(), Box<Error>> {
    let mut pool = Pool::new(2);

    pool.scoped(|scope| {
        scope.execute(move || {
            // This changed to become fallible
            fallible_code();
        });
    });

    Ok(())
}

fn fallible_code() -> Result<(), Box<Error + Send + Sync>> {
    Err(From::from("Failing"))
}
< p>最近fallible_code函数更改为返回一个Result,我想将错误从pool.scoped块传播到外部。然而,Scope::execute的签名不允许返回值:

fn execute<F>(&self, f: F) 
    where F: FnOnce() + Send + 'scope

我正在使用scoped_threadpool 0.1.7。

1个回答

2

我不知道这是否是一种特别惯用的方法,但至少有效的一种方法是将其分配给一个捕获的变量。

let mut pool = Pool::new(2);
let mut ret = Ok(());

pool.scoped(|scope| {
    scope.execute(|| {
        ret = fallible_code();
    });
});

ret.map_err(|x| x as Box<Error>)

显然,如果没有微不足道的默认值,你需要将ret变成Option类型。如果内部闭包必须是move,则需要明确指定ret_ref = &mut ret


@MatthieuM。这就是为什么需要ret.map_err(|x| x as Box <Error>)来匹配inner_main的返回类型。 - Veedrac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接