当前位置: 首页 > 工具软件 > async-std > 使用案例 >

Rust 异步编程 - async-std

吕向阳
2023-12-01

使用示例:

[dependencies]
futures = "0.3.8"


[dependencies.async-std]
version = "1.7.0"
features = ["attributes"]
use std::time;
use futures::future::{join,join_all};
use async_std::task;
use std::sync::{Arc,Mutex};


async fn hello(){
    println!("hello")
}


async fn connect_db() -> String{
    task::sleep(time::Duration::from_secs(1)).await;
    String::from("connect_db successfully")
}


async fn open_file() -> String{
    task::sleep(time::Duration::from_secs(1)).await;
    String::from("connect_db successfully")
}

async fn back_with_result() -> Result<String,()>{
    Ok(String::from("Result"))
}



async fn main_exe(){
    hello().await;
    let (db,filename) = join(connect_db(),open_file()).await;
    println!("====={},{}=========",db,filename);
    println!("====={}=========",back_with_result().await.unwrap())
}


async fn select_db(input:&str) -> String{
    task::sleep(time::Duration::from_secs(1)).await;
    format!("select :{}",input)
}


async fn get_cities() ->Vec<String>{
    let cities = vec![
        String::from("shanghai"),
        String::from("beijing"),
        String::from("guangzhou"),
        String::from("shenzhen")
    ];
    let city_vec:Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(vec![]));
    join_all(cities.into_iter().map(|city|{
        build_city(city_vec.clone(),city)
    })).await;
    return city_vec.lock().unwrap().clone();
}


async fn build_city(city_vec:Arc<Mutex<Vec<String>>>,city:String){
    task::sleep(time::Duration::from_secs(1)).await;
    println!("Super city build");
    city_vec.lock().unwrap().push(format!("china super city {}",city))
}



#[async_std::main]
async fn main() {
    let now = time::Instant::now();
    main_exe().await;
    println!("main!");


    let users = vec!["ma","hua","teng"];
    let user_info = join_all(users.into_iter().map(|user|{
       select_db(user)
    })).await;

    println!("users info : {:?}",user_info);
    println!("executed in {:?}!",now.elapsed());
    println!("{:?}!",get_cities().await);

}
 类似资料: