在rust 的异步项目中,经常看到用async、JoinHandle修饰的函数/方法,它们二者在异步开发中有什么区别,什么时候用async,什么时候用JoinHandle.
async 是rust Future的语法糖,主要用于定义 异步函数或异步代码块,编译器会将async 代码块在编译期生成对应的Future实现代码,它是lazy的不会自动执行任务,需要await才会触发函数或代码块运行。
下面2个do_something_**
的定义本质上是做同一件事情,
use std::future::Future;
async fn do_something_async() -> u64 {
32
}
fn do_something_future() -> impl Future<Output = u64> {
async { 32 }
}
#[tokio::main]
async fn main() {
println!("{}", do_something_async().await);
println!("{}", do_something_future().await);
}
async 主要用于定义 异步函数 或 异步代码块,它不会自动启动任务,而是返回一个 Future,需要 await 运行。
JoinHandle 是一个“等待某个任务执行完成并获得其结果”的句柄(Handle),创建后会线程内任务会立即执行、非lazy,当需要获取线程内任务执行结果时调用.join或.await。
标准库(std::thread)与异步运行时库(如 tokio)都提供了JoinHandle的语义,它们具有相同的执行语义:非lazy,获取内部异步任务结果时分别使用.join、.await。
fn main() {
thread_join();
async_runtime_join();
}
fn thread_join() {
let begin = std::time::Instant::now();
let handler = std::thread::spawn(|| (std::time::Instant::now(), "hello world".to_string()));
std::thread::sleep(std::time::Duration::from_secs(2));
let result = handler.join().unwrap();
let end = std::time::Instant::now();
assert_eq!(result.1, "hello world");
println!(
"begin: {:?}, thread completed {:?}, end: {:?}",
begin.elapsed().as_secs(),
result.0.elapsed().as_secs(),
end.elapsed().as_secs()
);
}
fn async_runtime_join() {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let begin = std::time::Instant::now();
let handler =
tokio::spawn(async { (std::time::Instant::now(), "hello world".to_string()) });
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
let result = handler.await.unwrap();
let end = std::time::Instant::now();
assert_eq!(result.1, "hello world");
println!(
"begin: {:?}, async thread completed {:?}, end: {:?}",
begin.elapsed().as_secs(),
result.0.elapsed().as_secs(),
end.elapsed().as_secs()
);
})
}
概念 | 作用 | 是否立即执行 | 如何获取结果 |
---|---|---|---|
async | 构建 Future | ❌ 不会 | 需要 .await |
Future | 异步操作描述符 | ❌ 不会 | .await |
JoinHandle | 表示一个异步任务的运行句柄 | ✅ 会执行 | .await 结果 |
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有