Hello there!
I'm trying to translate a library from C to Rust which is parsing USART data and calling different callbacks (depending on its state).
The code is for microcontroller so heapless:: is going to be used. I'm using std:: here for playground only.
Translated code is generating an error:
`(dyn for<'r> std::ops::FnMut(&'r [u8]) + 'static)` cannot be shared between threads safely
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
struct Parser {
cb: Option<&'static FnMut(&[u8])>,
}
impl Parser {
fn feed(&mut self, st: &[u8]) {
if let Some(f) = self.cb {
(f)(&st);
};
}
}
fn time_is_out() -> bool {
false
}
fn main() {
let mut parser: Parser = Parser { cb: None };
let p = Arc::new(Mutex::new(parser));
let p_parser = Arc::clone(&p);
let app_handle = thread::spawn(move || {
let state = 0;
let mut _parser = p_parser.lock().unwrap();
_parser.cb = Some(&|s| {
if s == b"CONNECT OK\r\n" {
state = 1
}
});
while state == 0 || !time_is_out() {
thread::sleep(Duration::from_millis(250));
}
_parser.cb = Some(&|s| {
if s == b"CONNECT FAIL\r\n" {
state = 1
}
});
while state == 0 || !time_is_out() {
thread::sleep(Duration::from_millis(250));
}
});
let p = Arc::new(Mutex::new(parser));
let p_parser = Arc::clone(&p);
let usart_handle = thread::spawn(move || {
let mut _parser = p_parser.lock().unwrap();
loop {
thread::sleep(Duration::from_millis(250));
_parser.feed(b"CONNECT OK\r\n");
}
});
usart_handle.join().unwrap();
app_handle.join().unwrap();
}