How can I cause a panic on a thread to immediately end the main thread?

前端 未结 2 1797

In Rust, a panic terminates the current thread but is not sent back to the main thread. The solution we are told is to use join. However, this blocks the curren

2条回答
  •  隐瞒了意图╮
    2020-12-11 03:40

    Updated for Rust 1.10+, see revision history for the previous version of the answer

    good point, in go the main thread doesn't get unwound, the program just crashes, but the original panic is reported. This is in fact the behavior I want (although ideally resources would get cleaned up properly everywhere).

    This you can achieve with the recently stable std::panic::set_hook() function. With it, you can set a hook which prints the panic info and then exits the whole process, something like this:

    use std::thread;
    use std::panic;
    use std::process;
    
    fn main() {
        // take_hook() returns the default hook in case when a custom one is not set
        let orig_hook = panic::take_hook();
        panic::set_hook(Box::new(move |panic_info| {
            // invoke the default handler and exit the process
            orig_hook(panic_info);
            process::exit(1);
        }));
    
        thread::spawn(move || {
            panic!("something bad happened");
        }).join();
    
        // this line won't ever be invoked because of process::exit()
        println!("Won't be printed");
    }
    

    Try commenting the set_hook() call out, and you'll see that the println!() line gets executed.

    However, this approach, due to the use of process::exit(), will not allow resources allocated by other threads to be freed. In fact, I'm not sure that Go runtime allows this as well; it is likely that it uses the same approach with aborting the process.

提交回复
热议问题