Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return an error from a scoped_threadpool thread?

I have some code that uses scoped_threadpool a bit like this:

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"))
}

The fallible_code function recently changed to return a Result, and I'd like to propagate the error outside of the pool.scoped block. However, the signature of Scope::execute doesn't allow for a return value:

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

I am using scoped_threadpool 0.1.7.

like image 443
Shepmaster Avatar asked Mar 01 '16 00:03

Shepmaster


1 Answers

I don't know if it's a particularly idiomatic method, but one method that at least works is assigning to a captured variable.

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>)

Obviously you'd need to make ret an Option or so if there is no trivial default. If the inner closure must be move, you'll need to make ret_ref = &mut ret explicit.

like image 167
Veedrac Avatar answered Sep 24 '22 03:09

Veedrac