use std::thread;
use std::time;
use tokio::time::{sleep,Duration};
fn blocking_call() -> String{
for idx in 0..5{
thread::sleep(time::Duration::from_secs(1));
println!("---{}",idx);
}
"Finally done".to_string()
}
async fn async_call(id: i32){
sleep(Duration::from_secs(1)).await;
println!("Async id:{}",id);
}
#[tokio::main]
async fn main() {
let blocking_call_handle = tokio::task::spawn_blocking(blocking_call);
let mut async_handles = Vec::new();
for id in 0..10{
async_handles.push(tokio::spawn(async_call(id)));
}
for handle in async_handles{
handle.await.unwrap();
}
println!("Hello, world!");
let result = blocking_call_handle.await.unwrap();
println!("Blocking result:{}",result);
}
---0
Async id:2
Async id:7
Async id:6
Async id:0
Async id:3
Async id:9
Async id:4
Async id:5
Async id:8
Async id:1
Hello, world!
---1
---2
---3
---4
Blocking result:Finally done
标签:---,tokio,学习,call,async,Async,id
From: https://www.cnblogs.com/hardfood/p/18245421