Skip to content

Instantly share code, notes, and snippets.

@jcbritobr
Created September 23, 2020 20:44
Show Gist options
  • Save jcbritobr/f6f5759e088664bf4197e0bb9c21c60f to your computer and use it in GitHub Desktop.
Save jcbritobr/f6f5759e088664bf4197e0bb9c21c60f to your computer and use it in GitHub Desktop.
Rust producer consumer pattern, sending functions between channels
use std::{sync::mpsc, thread};
type Closure = Box<dyn FnOnce() + Send + 'static>;
fn main() {
let (tx, rx) = mpsc::channel::<Closure>();
let handle = thread::spawn(move ||{
while let Ok(data) = rx.recv(){
data();
}
});
for i in 0..10 {
tx.send(Box::new(move ||{
println!("data:{}", i);
})).unwrap();
}
drop(tx);
handle.join().expect("cant merge thread");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment