From 80be61ed78e8410e013cb94879435d54a4907c30 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Sun, 2 Sep 2018 14:46:15 +0300 Subject: project model --- crates/server/src/thread_watcher.rs | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 crates/server/src/thread_watcher.rs (limited to 'crates/server/src/thread_watcher.rs') diff --git a/crates/server/src/thread_watcher.rs b/crates/server/src/thread_watcher.rs new file mode 100644 index 000000000..98bcdfd6c --- /dev/null +++ b/crates/server/src/thread_watcher.rs @@ -0,0 +1,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 + } +} -- cgit v1.2.3