1、异步
如下代码:先打印hhh,再打印my_function中的log。
#[tokio::main]
async fn main() {
let f = my_function();
println!("hhhhh");
f.await;
}
async fn my_function() {
println!("i am a async function");
let s1 = read_from_database().await;
println!("first result:{s1}");
let s2 = read_from_database().await;
println!("second result:{s2}");
}
async fn read_from_database() -> String {
"DB Result".to_owned()
}
最外层调用Future需要手动调用,所以用到了第三方库tokio,不然会报错main方法不能加async。三方库的作用是构建一个运行时并调用main方法。
/tokio = { version = "1.24.2", features = ["full"] }
2、并发
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
//#[tokio::main(flavor = "current_thread")]会强制tokio多任务都在一个线程-主线程
async fn main() {
let mut handles = vec![];
for i in 0..2 {
let handle = tokio::spawn(async move {
my_function(i).await;
});
handles.push(handle);
}
for handle in handles {
handle.await.unwrap();
}
}
async fn my_function(i: i32) {
println!("i am a async function");
let s1 = read_from_database().await;
println!("[{i}] first result:{s1}");
let s2 = read_from_database().await;
println!("[{i}] second result:{s2}");
}
async fn read_from_database() -> String {
sleep(Duration::from_millis(50)).await; //此处await缺失会变同步
"DB Result".to_owned()
}
网友评论