Updated 'src/async/multiple_futures.md'.

This commit is contained in:
Hector PENG
2026-04-11 18:56:56 +08:00
parent d50c9be81c
commit 3240c5d08c
6 changed files with 257 additions and 5 deletions

View File

@@ -0,0 +1,7 @@
[package]
name = "custom_async_abstraction"
version = "0.1.0"
edition = "2024"
[dependencies]
trpl = "0.3.0"

View File

@@ -0,0 +1,19 @@
use std::time::Duration;
fn main() {
let fut = async {
let slow = async {
trpl::sleep(Duration::from_secs(5)).await;
"最终完成"
};
match timeout(slow, Duration::from_secs(2)).await {
Ok(message) => println!("在 '{message}' 下成功"),
Err(duration) => {
println!("{} 秒后失败", duration.as_secs())
}
}
};
trpl::block_on(fut);
}

View File

@@ -0,0 +1,7 @@
[package]
name = "starvation_demo"
version = "0.1.0"
edition = "2024"
[dependencies]
trpl = "0.3.0"

View File

@@ -0,0 +1,38 @@
use std::{thread, time::Duration};
fn slow(name: &str, ms: u64) {
thread::sleep(Duration::from_millis(ms));
println!("'{name}' 运行了 {ms}ms");
}
fn main() {
let fut = async {
let a = async {
println!("'a' 已启动。");
slow("a", 30);
trpl::yield_now().await;
slow("a", 10);
trpl::yield_now().await;
slow("a", 20);
trpl::yield_now().await;
println!("'a' 已结束。");
};
let b = async {
println!("'b' 已启动。");
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;
println!("'b' 已结束。");
};
trpl::select(a, b).await;
};
trpl::block_on(fut);
}