如何从scoped_threadpool线程返回错误?

She*_*ter 5 error-handling rust

我有一些使用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"))
}
Run Code Online (Sandbox Code Playgroud)

fallible_code最近更改的函数返回a Result,我想在pool.scoped块之外传播错误.但是,签名Scope::execute不允许返回值:

fn execute<F>(&self, f: F) 
    where F: FnOnce() + Send + 'scope
Run Code Online (Sandbox Code Playgroud)

我正在使用scoped_threadpool 0.1.7.

Vee*_*rac 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>)
Run Code Online (Sandbox Code Playgroud)

显然,如果没有简单的默认值,您需要做出ret一个左右。Option如果内部闭包必须是move,则需要ret_ref = &mut ret明确说明。