说明

设置运行时将使用的工作线程数量。这个数字可以是大于0的任何数字,但建议将这个值保持在较小的范围内。这将覆盖从环境变量TOKIO_WORKER_THREADS读取的值。

use tokio::runtime;

// This will spawn a work-stealing runtime with 4 worker threads.
let rt = runtime::Builder::new_multi_thread()
    .worker_threads(4)
    .build()
    .unwrap();

rt.spawn(async move {});

例子

永远不会输出bb,因为只有一个调度线程被阻塞了

use std::net::ToSocketAddrs;

use tokio::{runtime, task};
use tokio::io::AsyncReadExt;

async fn Fun() {
    println!("11");
    loop {
        // 一直阻塞
    }
}

async fn Func1() {
    println!("aa");
    std::thread::sleep(std::time::Duration::from_secs(3));
    println!("bb");
}


#[tokio::main]
async fn main() {
    let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(1).build().unwrap();
    println!("start");
    runtime.spawn(Fun());
    runtime.spawn(Func1());
    println!("finish");
    loop {}
}

增加一个就可以了

use std::net::ToSocketAddrs;

use tokio::{runtime, task};
use tokio::io::AsyncReadExt;

async fn Fun() {
    println!("11");
    loop {
        // 一直阻塞
    }
}

async fn Func1() {
    println!("aa");
    std::thread::sleep(std::time::Duration::from_secs(3));
    println!("bb");
}


#[tokio::main]
async fn main() {
    let runtime = tokio::runtime::Builder::new_multi_thread().worker_threads(2).build().unwrap();
    println!("start");
    runtime.spawn(Fun());
    runtime.spawn(Func1());
    println!("finish");
    loop {}
}