【Tokio】設置工作線程數


環境

  • Time 2022-01-11
  • Rust 1.57.0
  • Tokio 1.15.0

概念

參考:https://docs.rs/tokio/latest/tokio/runtime/struct.Builder.html

默認情況下,Tokio 啟動的工作線程數和 CPU 核數相等,也可以自定義。

示例

main.rs

use std::{io, thread, time::Duration};

use tokio::runtime::Builder;

fn main() -> io::Result<()> {
    let runtime = Builder::new_multi_thread().worker_threads(4).build()?;

    runtime.spawn(async {
        println!("hello tokio");
        println!("{}", thread::current().name().unwrap());
    });

    println!("{}", thread::current().name().unwrap());
    thread::sleep(Duration::from_secs(4444));
    runtime.shutdown_timeout(Duration::from_secs(4));
    Ok(())
}

總結

使用 Builder 來定義異步運行時的工作線程數。

附錄


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM