douglas/
worker_thread.rs

1use crossbeam_channel::{unbounded, Receiver, Sender};
2use std::thread::{self, JoinHandle};
3
4/// Small abstraction around a closure that runs in another thread
5/// and waits for a channel to notify that it should stop.
6pub struct WorkerThread {
7    handle: JoinHandle<()>,
8    done: Sender<()>,
9}
10
11impl WorkerThread {
12    /// Spawn a worker closure in a new thread.
13    pub fn spawn<F>(fun: F) -> Self
14    where
15        F: FnOnce(Receiver<()>) + Send + 'static,
16    {
17        let (tx, rx) = unbounded::<()>();
18        let handle = thread::spawn(move || fun(rx));
19
20        Self { handle, done: tx }
21    }
22
23    /// Notify a running worker that it should stop, then block
24    /// until it returns.
25    pub fn close(self) {
26        self.done.send(()).unwrap();
27        self.handle.join().unwrap();
28    }
29}