为什么我的阻塞线程在另一个线程输出一次之前输出两次?我希望能够生成任务以在后台运行(立即),但在主代码继续之前不等待它们完成。有没有一种简单的方法可以做到这一点tokio?
代码:
use std::{thread, time};
use chrono;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Starting up");
    tokio::spawn(blocking_thread()).await.unwrap();
    Ok(())
}
async fn blocking_thread() {
    for i in 1..5 {
        println!("{} Blocking thread {}", chrono::offset::Utc::now(), i);
        tokio::spawn(other_thread(i));
        thread::sleep(time::Duration::from_millis(100)); //In my real code this is a blocking syscall
    }
}
async fn other_thread(i: u8) {
    println!("{} Other thread {}", chrono::offset::Utc::now(), i);
}
输出:
Starting up
2022-01-21 09:03:36.662248332 UTC Blocking thread 1
2022-01-21 09:03:36.762375086 UTC Blocking thread 2
2022-01-21 09:03:36.762617994 UTC Other thread 1
2022-01-21 09:03:36.862634161 UTC Blocking thread 3
2022-01-21 09:03:36.862913141 UTC Other thread 2
2022-01-21 09:03:36.963055279 UTC Blocking thread 4
2022-01-21 09:03:36.963383710 UTC Other thread 3
2022-01-21 09:03:37.063496911 UTC Other thread 4
为什么我的阻塞线程在其他线程输出一次之前输出两次
用于tokio::time::sleep在室内睡觉blocking_thread。因为 thread::sleep 不会让主 tokio 执行器执行。
我希望能够生成任务以在后台运行(立即),但在主代码继续之前不等待它们完成。
您正在在线等待tokio::spawn(blocking_thread()).await.unwrap();线程完成。await如果您想继续主要内容,请不要这样做。