I would like to send a closure via channels:
use std::thread;
use std::sync::mpsc;
#[derive(Debug)]
struct Test {
s1: String,
s2: String,
}
fn main() {
The accepted answer doesn't go into detail, but you can send closures to threads via channels, even on stable, if you don't use FnOnce
:
use std::thread;
use std::sync::mpsc;
struct RawFunc {
data: Box,
}
impl RawFunc {
fn new(data: T) -> RawFunc
where
T: Fn() + Send + 'static,
{
return RawFunc {
data: Box::new(data),
};
}
fn invoke(self) {
(self.data)()
}
}
fn main() {
// Local
let x = RawFunc::new(move || {
println!("Hello world");
});
x.invoke();
// Via channel
let (sx, rx) = mpsc::channel::();
sx.send(RawFunc::new(move || {
println!("Hello world 2");
})).unwrap();
let output = rx.recv().unwrap();
output.invoke();
// In a thread
let guard = thread::spawn(move || {
let output = rx.recv().unwrap();
output.invoke();
});
sx.send(RawFunc::new(move || {
println!("Hello world 3!");
})).unwrap();
guard.join().unwrap();
// Passing arbitrary data to a thread
let (sx, rx) = mpsc::channel::();
let guard = thread::spawn(move || {
let output = rx.recv().unwrap();
output.invoke();
});
let foo = String::from("Hello World 4");
sx.send(RawFunc::new(move || {
println!("Some moved data: {:?}", foo);
})).unwrap();
guard.join().unwrap();
}