Rust异步编程入门
理解async/.await语法、Future trait以及运行时(如tokio)的基础使用 · 难度:入门 · +15XP
异步编程基础
Rust的异步编程基于Future trait,通过async和.await实现非阻塞并发。异步任务在等待I/O时让出线程,提高效率。
async/.await语法
use tokio::time::{sleep, Duration};
async fn do_something() {
println!("开始任务");
sleep(Duration::from_secs(1)).await;
println!("任务完成");
}
#[tokio::main]
async fn main() {
do_something().await;
}
Future trait
一个Future代表一个可能尚未完成的值。当调用.await时,如果Future未就绪,当前任务将被挂起,让出线程。
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
struct MyFuture;
impl Future for MyFuture {
type Output = i32;
fn poll(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(42)
}
}
运行时(tokio)
异步任务需要运行时驱动,tokio是最流行的异步运行时。
| 概念 | 说明 |
|---|---|
| async fn | 定义异步函数,返回Future |
| .await | 等待Future完成,挂起当前任务 |
| tokio::spawn | 在运行时中创建新任务 |
| join! | 并发等待多个Future |
练习提示
使用tokio编写一个异步函数,并发执行两个任务:一个打印1到3(每秒一个),另一个打印A到C(每秒一个),使用join!或tokio::join!。