Skip to content

Instantly share code, notes, and snippets.

@envis10n
Created February 11, 2019 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save envis10n/88bad68923173b046256a88bc4c74d92 to your computer and use it in GitHub Desktop.
Save envis10n/88bad68923173b046256a88bc4c74d92 to your computer and use it in GitHub Desktop.
Event loop in Rust using Tokio, futures, and mpsc channels.
type Closure = Box<Fn() + Send>;
fn main() {
let (tx, rx) = std::sync::mpsc::channel::<Closure>();
let eventloop = futures::future::lazy(move || {
loop {
if let Ok(call) = rx.recv() {
tokio::spawn(futures::future::lazy(move || {
call();
futures::future::ok::<(), ()>(())
}));
}
}
futures::future::ok::<(), ()>(())
});
std::thread::spawn(move || {
let mut count: i32 = 0;
loop {
tx.send(Box::new(||{
println!("Hello world!");
})).unwrap();
count += 1;
if count >= 5 {
break;
} else {
std::thread::sleep(std::time::Duration::new(5, 0));
}
}
});
// Start the event loop
tokio::run(eventloop);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment