aboutsummaryrefslogtreecommitdiff
path: root/crates/server/src/thread_watcher.rs
blob: 98bcdfd6c2f43fcba211b70b317cd7547fca5d6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
use std::thread;
use drop_bomb::DropBomb;
use Result;

pub struct ThreadWatcher {
    name: &'static str,
    thread: thread::JoinHandle<()>,
    bomb: DropBomb,
}

impl ThreadWatcher {
    pub fn spawn(name: &'static str, f: impl FnOnce() + Send + 'static) -> ThreadWatcher {
        let thread = thread::spawn(f);
        ThreadWatcher {
            name,
            thread,
            bomb: DropBomb::new(format!("ThreadWatcher {} was not stopped", name)),
        }
    }

    pub fn stop(mut self) -> Result<()> {
        info!("waiting for {} to finish ...", self.name);
        let name = self.name;
        self.bomb.defuse();
        let res = self.thread.join()
            .map_err(|_| format_err!("ThreadWatcher {} died", name));
        match &res {
            Ok(()) => info!("... {} terminated with ok", name),
            Err(_) => error!("... {} terminated with err", name)
        }
        res
    }
}