2016-03-01 35 views
5

我有一個使用scoped_threadpool有點像這樣一些代碼:如何從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")) 
} 

fallible_code功能最近改爲返回Result,我想傳播pool.scoped塊之外的錯誤。然而,Scope::execute簽名不允許返回值:

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

我使用scoped_threadpool 0.1.7。

回答

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

顯然,你需要做一個retOption所以如果沒有平凡缺省。如果內部封閉必須是move,則需要明確地指定ret_ref = &mut ret

+0

這個想法聽起來不錯,但不應該''同步'? –

+0

@MatthieuM。這就是爲什麼'ret.map_err(| x | x作爲方框)'來匹配'inner_main'的返回類型的原因。 – Veedrac