xref: /NovaShell/src/shell/thread_manager.rs (revision 7bb802ad1ee86687164e3577e7cb403d89b94963)
1 use std::{
2     sync::mpsc::{Receiver, RecvError, SendError, Sender},
3     thread::{self, JoinHandle, ThreadId},
4 };
5 
6 pub struct ThreadManager<S, R> {
7     handle: Option<JoinHandle<()>>,
8     sender: Sender<S>,
9     receiver: Receiver<R>,
10 }
11 
12 impl<S, R> ThreadManager<S, R> {
new<F>(f: impl FnOnce() -> (Sender<S>, Receiver<R>, F)) -> ThreadManager<S, R> where F: FnOnce() -> (), F: Send + 'static,13     pub fn new<F>(f: impl FnOnce() -> (Sender<S>, Receiver<R>, F)) -> ThreadManager<S, R>
14     where
15         F: FnOnce() -> (),
16         F: Send + 'static,
17     {
18         let (s, r, func) = f();
19         let handle = thread::spawn(func);
20 
21         Self {
22             handle: Some(handle),
23             sender: s,
24             receiver: r,
25         }
26     }
27 
send(&self, item: S) -> Result<(), SendError<S>>28     pub fn send(&self, item: S) -> Result<(), SendError<S>> {
29         self.sender.send(item)
30     }
31 
receiver(&self) -> Result<R, RecvError>32     pub fn receiver(&self) -> Result<R, RecvError> {
33         self.receiver.recv()
34     }
35 
id(&self) -> Option<ThreadId>36     pub fn id(&self) -> Option<ThreadId> {
37         Some(self.handle.as_ref()?.thread().id())
38     }
39 
name(&self) -> Option<&str>40     pub fn name(&self) -> Option<&str> {
41         self.handle.as_ref()?.thread().name()
42     }
43 
join(&mut self) -> Result<(), ()>44     pub fn join(&mut self) -> Result<(), ()> {
45         if self.handle.is_none() {
46             return Ok(());
47         }
48         self.handle.take().unwrap().join().map_err(|_| ())
49     }
50 
is_finished(&mut self) -> bool51     pub fn is_finished(&mut self) -> bool {
52         if let Some(ref handle) = self.handle {
53             handle.is_finished()
54         } else {
55             true
56         }
57     }
58 }
59