从 Rust 线​​程中的闭包内传播错误

pic*_*ard 8 error-handling multithreading rust

我想从调用thread::spawn.

我曾尝试使用 aJoinHandle来捕获 的结果thread::spawn,但我在这样做时遇到了各种错误。

fn start_server(args) -> Result<(), Box<dyn std::error::Error>> {
    ...
    thread::spawn(move || {
        // I want to do this (put a ? after run_server)
        run_server(args)?;
        ...
    }
    ...        
});
Run Code Online (Sandbox Code Playgroud)
fn run_server(args) -> Result<(), std::io::Error> {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我收到这条消息

fn start_server(args) -> Result<(), Box<dyn std::error::Error>> {
    ...
    thread::spawn(move || {
        // I want to do this (put a ? after run_server)
        run_server(args)?;
        ...
    }
    ...        
});
Run Code Online (Sandbox Code Playgroud)

Web*_*rix 7

我想从调用 thread::spawn 的闭包内调用的函数传播错误

由于线程并行运行,从线程范围抛出错误是没有意义的。更好的方法是线程本身的错误处理。

所以通常你不应该将错误传播到线程上方的上层。

然而,你可以把你的error,你在你的并行获得threads后您joined到您main thread。这样它就很像同步中的错误传播。

以下是您可以如何管理它:

fn start_server() -> Result<(), Box<std::error::Error>> {
    let x = std::thread::spawn(move || -> Result<(), std::io::Error> {
        run_server()?;
        Ok(())
    });

    x.join().unwrap()?; // Now you can throw your error up because you joined your thread.
                        // ...
    Ok(())
}

fn run_server() -> Result<(), std::io::Error> {
    Err(std::io::Error::new(std::io::ErrorKind::Other, "hello"))
}

fn main() {
    let x = start_server();
    println!("{:?}", x);
}
Run Code Online (Sandbox Code Playgroud)

操场