環境
- 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
來定義異步運行時的工作線程數。