Created
September 23, 2020 20:44
-
-
Save jcbritobr/f6f5759e088664bf4197e0bb9c21c60f to your computer and use it in GitHub Desktop.
Rust producer consumer pattern, sending functions between channels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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