Crate panic_monitor [] [src]

panic_monitor helps you monitor your threads and deal with panics.

You might be tempted to use libstd's JoinHandles for this use-case; however, they have two major limitations:

  • JoinHandle::join blocks the current thread. If you want to monitor multiple threads from a single "supervisor" thread, you would need something like try_join, and ideally you'd have an "epoll for JoinHandles" as well to avoid busy-waiting. JoinHandle doesn't implement these, however.
  • You can't clone a JoinHandle. If you want multiple threads to be notified when a particular thread panics, you can't use its JoinHandle to achieve it.

panic_monitor handles both of these issues. PanicMonitor::wait allows you to specify a number of threads. As soon as one of them panics, it returns a Thread struct (which contains the name and ID of the panicking thread). When calling PanicMonitor::wait, you specify the watch-list in terms of ThreadIds. Since these are clonable, mulitple supervisor threads can monitor the same worker thread.

Some other differences between PanicMonitor::wait and JoinHandle::join:

  • You don't receive the value which was passed to panic. (This would be impossible, given that such values are not required to implement Clone.)
  • You aren't notified when a thread shuts down normally. PanicMonitor is for handling panicking threads only.

Usage

Create a global PanicMonitor using lazy_static, and initialise it from your main thread. Ideally you should do this before spawning any new threads.

#[macro_use] extern crate lazy_static;
extern crate panic_monitor;

use panic_monitor::PanicMonitor;
use std::thread;
use std::time::Duration;

lazy_static! {
    static ref PANIC_MONITOR: PanicMonitor = PanicMonitor::new();
}

fn main() {
    // Install a panic hook
    PANIC_MONITOR.init();

    let h = thread::spawn(|| {
        thread::sleep(Duration::from_millis(100));
        panic!();
    });

    PANIC_MONITOR.wait(&[h.thread().id()]);
    // ^ this will block until the thread panics

    PANIC_MONITOR.wait(&[h.thread().id()]);
    // ^ this will return immediately, since the thread is already dead

    h.join().unwrap_err();
}

Structs

PanicMonitor

A list of all threads which have panicked, with the ability to notify interested parties when this list is updated.