summaryrefslogtreecommitdiffstats
path: root/src/multi_futures
diff options
context:
space:
mode:
authorhybrid <hybrid@hybridlabs.cc>2026-10-31 03:54:43 +0300
committerhybrid <hybrid@hybridlabs.cc>2026-10-31 03:54:43 +0300
commit62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2 (patch)
treeb8461eda6cce3f9bbfb2261dd828077e17c7d226 /src/multi_futures
parent18ad654357d6cca34782aaa269f5e8e06cbe9241 (diff)
downloadrust-book-62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2.tar.gz
rust-book-62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2.tar.bz2
rust-book-62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2.zip
add: 7 craits
smartpointers interior_mutability threads mutex hello-async async_concurrency multi_futures
Diffstat (limited to 'src/multi_futures')
-rw-r--r--src/multi_futures/Cargo.toml7
-rw-r--r--src/multi_futures/src/main.rs61
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),
+ }
+}