diff options
Diffstat (limited to '')
| -rw-r--r-- | src/multi_futures/Cargo.toml | 7 | ||||
| -rw-r--r-- | src/multi_futures/src/main.rs | 61 |
2 files changed, 68 insertions, 0 deletions
diff --git a/src/multi_futures/Cargo.toml b/src/multi_futures/Cargo.toml new file mode 100644 index 0000000..c8d3a70 --- /dev/null +++ b/src/multi_futures/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "multi_futures" +version = "0.1.0" +edition = "2024" + +[dependencies] +trpl = "0.3.0" diff --git a/src/multi_futures/src/main.rs b/src/multi_futures/src/main.rs new file mode 100644 index 0000000..918e341 --- /dev/null +++ b/src/multi_futures/src/main.rs @@ -0,0 +1,61 @@ +use std::{thread, time::Duration}; +use trpl::{self, Either}; + +fn main() { + trpl::block_on(async{ + let a = async { + println!("'a' started."); + slow("a", 30); + trpl::yield_now().await; + slow("a", 10); + trpl::yield_now().await; + slow("a", 20); + trpl::yield_now().await; + trpl::sleep(Duration::from_millis(50)).await; + println!("'a' finished."); + }; + + let b = async { + println!("'b' started."); + slow("b", 75); + trpl::yield_now().await; + slow("b", 10); + trpl::yield_now().await; + slow("b", 15); + trpl::yield_now().await; + slow("b", 350); + trpl::yield_now().await; + trpl::sleep(Duration::from_millis(50)).await; + println!("'b' finished."); + }; + + trpl::select(a, b).await; + + let slow = async { + trpl::sleep(Duration::from_secs(2)).await; + "Finally finished" + }; + + match timeout(slow, Duration::from_secs(5)).await { + Ok(message) => println!("Succeeded with '{message}'"), + Err(duration) => { + println!("Failed after {} seconds", duration.as_secs()) + } + } + }); +} + +fn slow(name: &str, ms: u64) { + thread::sleep(Duration::from_millis(ms)); + println!("'{name}' ran for {ms}ms"); +} + +async fn timeout<F: Future>( + future_to_try: F, + max_time: Duration, +) -> Result<F::Output, Duration> { + match trpl::select(future_to_try, trpl::sleep(max_time)).await { + Either::Left(output) => Ok(output), + Either::Right(_) => Err(max_time), + } +} |
