面试题答案
一键面试代码示例
use std::time::Duration;
async fn async_task() {
// 模拟异步操作,这里使用`tokio::time::sleep`
tokio::time::sleep(Duration::from_secs(2)).await;
println!("异步任务执行完成");
}
#[tokio::main]
async fn main() {
// 创建异步任务
let task = async_task();
// 等待异步任务执行完成
task.await;
println!("主线程等待异步任务结束后继续执行");
}
async
函数和await
关键字的作用
async
函数:async
关键字用于定义异步函数。异步函数返回一个实现了Future
trait的值。在上述代码中,async fn async_task()
定义了一个异步任务,这个任务内部模拟了一个异步操作(通过tokio::time::sleep
)。异步函数并不会立即执行其中的代码,而是返回一个Future
,只有当这个Future
被.await
或通过其他方式驱动时才会真正执行。
await
关键字:await
关键字用于暂停当前异步函数的执行,直到其等待的Future
完成。在async_task
函数中,tokio::time::sleep(Duration::from_secs(2)).await;
这行代码中,await
使得async_task
函数暂停执行,直到tokio::time::sleep
所代表的异步操作(睡眠2秒)完成。在main
函数中,task.await;
等待async_task
返回的Future
执行完毕,只有当async_task
任务完成后,main
函数才会继续执行后续的代码。
注意,上述代码使用了tokio
运行时,需要在Cargo.toml
文件中添加tokio = { version = "1", features = ["full"] }
依赖。