Created
February 11, 2019 22:18
-
-
Save envis10n/88bad68923173b046256a88bc4c74d92 to your computer and use it in GitHub Desktop.
Event loop in Rust using Tokio, futures, and mpsc 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
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