Skip to content

异步编程

主要用于提高 I/O 密集型程序的并发性能,避免阻塞线程,从而提升整体执行效率。

异步编程机制通过非阻塞 I/O 提升 I/O 密集型应用的并发性能,适合构建高性能、高并发的网络服务等场景。

use std::fs;
#[tokio::main]
async fn main() {
// 写入文件
// fs::write("read.txt", "Hello").unwrap();
// 读取文件
// let result = fs::read_to_string("read.txt");
// match result {
// Ok(content) => println!("File content: {}", content),
// Err(e) => println!("Failed to read file: {}", e),
// }
let result = tokio::fs::read_to_string("read.txt").await;
match result {
Ok(content) => println!("File content: {}", content),
Err(e) => println!("Failed to read file: {}", e),
}
}
#[tokio::main]
async fn main() {
// say_hello().await;
// say_goodbye().await;
// 同时运行两个异步函数
// tokio::join!(say_hello(), say_goodbye(),);
// 同时运行两个异步函数,哪个先完成就执行哪个
tokio::select! {
result = say_name() => {
println!("Name: {}", result);
}
_ = tokio::time::sleep(tokio::time::Duration::from_millis(500)) => {
println!("Timeout");
}
}
// let handle = tokio::spawn(async {
// println!("Je suis un thread");
// });
// handle.await.unwrap();
}
async fn say_hello() {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
println!("Hello, world!");
}
async fn say_goodbye() {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
println!("Goodbye, world!");
}
async fn say_name() -> &'static str {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
"John"
}