How to return an error from scoped_threadpool stream?

I have code that uses scoped_threadpool something 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 fallible_code recently changed to return a Result , and I would like to propagate the error outside the pool.scoped block. However, the signature of Scope::execute does not allow returning the value:

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

I am using scoped_threadpool 0.1.7.

+5
source share
1 answer

I don't know if this is a particularly idiomatic method, but one method that at least works assigns 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 need to do ret a Option or so if there is no trivial default value. If the inner closure should be move , you need to make explicit ret_ref = &mut ret .

+2
source

Source: https://habr.com/ru/post/1244159/


All Articles