Skip to content

Instantly share code, notes, and snippets.

@gpwclark
Forked from rust-play/playground.rs
Last active December 6, 2022 21:38
Show Gist options
  • Save gpwclark/753b7b189391c5023bc347444fef1432 to your computer and use it in GitHub Desktop.
Save gpwclark/753b7b189391c5023bc347444fef1432 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use futures::{StreamExt as _, stream};
use tokio::time::sleep;
use tokio::time::{Instant, Duration};
async fn loopnprint(name: &str) -> Result<(), String> {
let now = Instant::now();
loop {
sleep(Duration::from_millis(101)).await;
let elapsed = Instant::now() - now;
if name == "task2" && elapsed > Duration::from_millis(1230) {
return Err("OHNO".to_string());
}
println!("name: {name}, delayed: {:?}.", elapsed);
}
}
async fn and_loop() -> Result<(), String> {
let mut s = stream::FuturesUnordered::new();
s.push(loopnprint("task2"));
s.push(loopnprint("task0"));
s.push(loopnprint("task1"));
while let Some(f) = s.next().await {
return f;
}
Ok(())
}
#[tokio::main]
async fn main() {
let ret = and_loop().await;
println!("RET: {:?}", ret);
sleep(Duration::from_millis(1000)).await;
println!("There should be no more prints!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment