Created
July 30, 2022 21:34
-
-
Save NF1198/be3c8337c4a314b0cad2e35de0d00651 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::sync::mpsc::SendError; | |
use std::sync::mpsc::{self}; | |
use std::thread; | |
use std::time::Duration; | |
#[derive(Debug)] | |
enum MonitorCommand { | |
Stop, | |
} | |
#[allow(dead_code)] | |
struct Monitor { | |
send_ch: mpsc::Sender<MonitorCommand>, | |
thread_join_handle: Option<std::thread::JoinHandle<()>>, | |
} | |
#[allow(dead_code)] | |
impl Monitor { | |
fn new() -> Monitor { | |
let (tx, rx) = mpsc::channel(); | |
let tjh = thread::spawn(move || { | |
let d = Duration::from_millis(250); | |
loop { | |
match rx.recv_timeout(d) { | |
Ok(MonitorCommand::Stop) => { | |
break; | |
} | |
Err(_err) => { | |
// ... keep running ... | |
} | |
} | |
println!("monitor is running..."); | |
} | |
println!("monitor has stopped.") | |
}); | |
Monitor { | |
send_ch: tx, | |
thread_join_handle: Option::Some(tjh), | |
} | |
} | |
fn send(&self, cmd: MonitorCommand) -> Result<(), SendError<MonitorCommand>> { | |
println!("Monitor was sent command: {:?}", cmd); | |
self.send_ch.send(cmd) | |
} | |
fn is_done(&mut self) -> bool { | |
match self.thread_join_handle.take() { | |
Some(tjh) => { | |
return tjh.is_finished(); | |
} | |
None => return true, | |
} | |
} | |
fn join(&mut self) { | |
self.send(MonitorCommand::Stop) | |
.expect("invalid monitor send channel"); | |
match self.thread_join_handle.take() { | |
Some(tjh) => match tjh.join() { | |
Ok(_) => {} | |
Err(_) => { | |
eprintln!("{}", "error joining monitor") | |
} | |
}, | |
None => {} | |
} | |
} | |
} | |
impl Drop for Monitor { | |
fn drop(&mut self) { | |
match self.send(MonitorCommand::Stop) { | |
Ok(_) => {} | |
Err(err) => { | |
eprintln!("{}", err) | |
} | |
} | |
} | |
} | |
fn main() { | |
{ | |
let _m = Monitor::new(); | |
std::thread::sleep(Duration::from_millis(1000)); | |
println!("scope is closing..."); | |
} | |
println!("scope has closed"); | |
std::thread::sleep(Duration::from_millis(500)); | |
println!("program done"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code implements the monitor pattern in Rust.