Skip to content

Instantly share code, notes, and snippets.

@NF1198
Created July 30, 2022 21:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NF1198/be3c8337c4a314b0cad2e35de0d00651 to your computer and use it in GitHub Desktop.
Save NF1198/be3c8337c4a314b0cad2e35de0d00651 to your computer and use it in GitHub Desktop.
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");
}
@NF1198
Copy link
Author

NF1198 commented Jul 30, 2022

This code implements the monitor pattern in Rust.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment