同步编程:按程序编写的顺序执行,如果操作不能立即获得执行结果,会一直阻塞直到获取到结果。
异步编程:如果操作不能立即获得执行结果,操作会挂起到后台,执行线程不阻塞,继续执行其他操作任务。一旦操作完成,操作恢复,从中断的地方继续执行。
rust异步编程使用async和await关键字。
async:标识函数为异步, async标识的函数会编译成异步执行例程。
await:对返回值执行await时,才执行异步操作。这里的返回值是指调用异步函数的返回值,该返回值标识这个异步操作。
例子
async fn say_world() {
println!("world");
}
#[tokio::main]
async fn main() {
// Calling `say_world()` does not execute the body of `say_world()`.
let op = say_world();
// This println! comes first
println!("hello");
// Calling `.await` on `op` starts executing `say_world`.
op.await;
}
输出
hello
world
有3点需要重点理解
#[tokio::main]
async fn main() {
println!("hello");
}
相比正常main函数有2点不同:
#[tokio::main]这是一个注释宏,会将异步main函数转换为同步main函数,初始化运行时,并执行异步main函数。
#[tokio::main]
async fn main() {
println!("hello");
}
转化为
fn main() {
let mut rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
println!("hello");
})
}