小编Ste*_*eve的帖子

为什么 tokio 线程在继续之前要等待阻塞线程?

为什么我的阻塞线程在另一个线程输出一次之前输出两次?我希望能够生成任务以在后台运行(立即),但在主代码继续之前不等待它们完成。有没有一种简单的方法可以做到这一点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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

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 …
Run Code Online (Sandbox Code Playgroud)

rust rust-tokio

1
推荐指数
1
解决办法
2155
查看次数

标签 统计

rust ×1

rust-tokio ×1