mirror of
https://github.com/gnu4cn/rust-lang-zh_CN.git
synced 2026-08-19 04:33:27 +08:00
Updated 'src/async/multiple_futures.md'.
This commit is contained in:
7
projects/custom_async_abstraction/Cargo.toml
Normal file
7
projects/custom_async_abstraction/Cargo.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "custom_async_abstraction"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
trpl = "0.3.0"
|
||||
19
projects/custom_async_abstraction/src/main.rs
Normal file
19
projects/custom_async_abstraction/src/main.rs
Normal 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);
|
||||
}
|
||||
7
projects/starvation_demo/Cargo.toml
Normal file
7
projects/starvation_demo/Cargo.toml
Normal file
@@ -0,0 +1,7 @@
|
||||
[package]
|
||||
name = "starvation_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
trpl = "0.3.0"
|
||||
38
projects/starvation_demo/src/main.rs
Normal file
38
projects/starvation_demo/src/main.rs
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user