Rust: tokio初试

toml:

[dependencies]
tokio = { version = "1", features = ["full"] }
futures = "0.3.4"

代码:

use std::time::{Duration, Instant};
use std::thread;
use tokio::time;

async fn hello_world() {
    println!("hello world!");
}
// 同步sleep
async fn sync_time_01() {
    std::thread::sleep(time::Duration::from_secs(1));//同步sleep
}
async fn sync_time_02() {
    std::thread::sleep(time::Duration::from_secs(1))//同步sleep
}
// 异步sleep
async fn async_time_01() {
    tokio::time::sleep(Duration::from_secs(1)).await;//异步sleep
}
async fn async_time_02() {
    tokio::time::sleep(Duration::from_secs(1)).await;//异步sleep
}
async fn sync_do() {
    hello_world().await;
    tokio::join!(sync_time_01(),sync_time_02());// 并行跑
    println!("sync_do is over!")
}

async fn async_do() {
    hello_world().await;
    tokio::join!(async_time_01(),async_time_02(),async_time_01(),async_time_02());//并行跑
    println!("async_do is over!")
}

#[tokio::main]
async fn main() {
    let start_1 = Instant::now();
    sync_do().await;
    println!("sync_do cost miliseconds[毫秒] : {}", start_1.elapsed().as_millis());
    let start_2 = Instant::now();
    async_do().await;
    println!("async_do cost miliseconds[毫秒] : {}", start_2.elapsed().as_millis());

}

你可能感兴趣的:(Rust)