I'm trying to pass a string to a crossbeam channel that is called via a cross thread callback. apparently rust doesn't like this and throws an error. i probably can fix it using 'static but the text i'm not sure if that is the right way of doing it since i only want to move it to .send. any idea?
use std::thread;
use std::time::Duration;
use crossbeam::channel::{unbounded, Sender};
type CallbackType = Box<dyn Fn(String) + Send + Sync + 'static>;
fn callback_container(callback: &CallbackType) {
callback("Deep in thread".to_string());
}
fn relay(callback: CallbackType) {
let mut planner = periodic::Planner::new();
planner.add(
move || callback_container(&callback),
periodic::After::new(Duration::from_secs(5)),
);
planner.start();
drop(planner)
}
fn mycallback(text: String, sender: &Sender<&'static str>) {
sender.send(&text);
}
fn main() {
let (sender, receiver) = unbounded();
let sender2 = sender.clone();
thread::spawn(move || {
sender2.send("level 1");
relay(Box::new(move | text: String | mycallback(text, &sender2)));
});
thread::spawn(move || {
loop {
println!("{}", receiver.recv().unwrap()); // Received immediately
}
});
loop {
thread::sleep(Duration::from_secs(2)); // block for two seconds
}
}