I am writing an application which should read from a serial port in a loop (like a watcher) and also write commands to it.
The main thread is allowed to only write while the created thread can only read.
I created a simple example to reproduce my problem here. tx_thread
reads from the serial port in a loop and on a certain condition it sends a message via MPSC channel. rx_thread
looks for messages; when there is anything available it processes and it should also mutate the current state of the struct.
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
// this will also implement Drop trait to wait threads to
// be finished (message will be Enum instead of number in this case)
#[derive(Debug)]
struct MyStruct {
num: u32,
tx_thread: Option<thread::JoinHandle<()>>,
rx_thread: Option<thread::JoinHandle<()>>,
}
impl MyStruct {
fn new() -> MyStruct {
MyStruct {
num: 0,
tx_thread: None,
rx_thread: None,
}
}
fn start(&mut self) {
let (tx, rx) = mpsc::channel();
// tx thread will read from serial port infinitely,
// and send data to mpsc channel after certain condition
// to be processed.
let tx_thread = thread::spawn(move || {
let mut i = 0;
loop {
tx.send(i).unwrap();
i += 1;
thread::sleep(Duration::from_secs(1));
}
});
// after this will receive message, it will start
// processing and mutate `self` state if needed.
let rx_thread = thread::spawn(move || loop {
let num = rx.recv().unwrap();
println!("{:?}", num);
/* here, how do I save `num` to `self`? */
thread::sleep(Duration::from_secs(1));
});
self.tx_thread = Some(tx_thread);
self.rx_thread = Some(rx_thread);
}
}
fn main() {
let mut s = MyStruct::new();
s.start();
thread::sleep(Duration::from_secs(999999));
}