【Rust】Tokioとは?

Node.jsとGolangを合体させたもの
膨大なリクエストをシングルスレッド&イベントループ&非同期I/Oで効率よく処理するランタイム(ライブラリ)
tokioではOSではなくランタイムがタスクのスケジューリングを行う。タスク生成はtokio::spawnを呼び出す

use std::time::Duration;

#[tokio::main]
async fn main() {
    tokio::task::spawn(async {
        tokio::time::sleep(Duration::from_secs(2)).await;
        println!("Done");
    });

    std::thread::sleep(Duration::from_secs(3));
    println!("wake up");
}

シングルスレッド

use std::time::Duration;

#[tokio::main(flavor="current_thread")]
async fn main() {
    tokio::task::spawn(async {
        tokio::time::sleep(Duration::from_secs(2)).await;
        println!("Done");
    });

    std::thread::sleep(Duration::from_secs(3));
    println!("wake up");
}
use std::time::Duration;

#[tokio::main(flavor="multi_thread", worker_threads = 1)]
async fn main() {
    let cpus = num_cpus::get();
    println!("logical cores: {}", cpus);

    tokio::task::spawn(async move {
        println!("task 1 started..");
        tokio::time::sleep(Duration::from_secs(3)).await;
        println!("task 1 wake up");
    });

    tokio::task::spawn(async move {
        println!("task 2 started..");
        tokio::time::sleep(Duration::from_secs(1)).await;
        println!("task 2 wake up");
    });

    tokio::time::sleep(Duration::from_secs(5)).await;
    println!("wake up");
}

task 1 started..
task 2 started..
task 2 wake up
task 1 wake up
wake up

use std::time::Duration;
use futures::{stream::FuturesUnordered, StreamExt};
use std::thread;

#[tokio::main(flavor="multi_thread", worker_threads = 1)]
async fn main() {
    // console_subscriber::init();

    let mut tasks = FuturesUnordered::new();

    let h1 = tokio::spawn(async move {
        thread::sleep(Duration::from_secs(10)).await;
        println!("0 wake up");
    });
    tasks.push(h1);
    println!("0 started...");

    for i in 1..100 {
        let h2 = tokio::spawn(async move {
            tokio::time::sleep(Duration::from_secs(1)).await;
            println!("{i} woke up!");
        });
        tasks.push(h2);
        println!("{i} ...");
    }
    while let Some(item) = tasks.next().await {
        let () = item.unwrap();
    }
    println!("Done");
}