Tokio::spawn run directly or not ? await got different results

i want to test tokio::spawn run future directly or not , this is my code . When i run this code muiltple times , i got different results , sometimes i got just "test_tokio_spawn "output , but sometimes i got "test_tokio_spawn " and "Hello, world!" !

fn main() {
//create tokio::runtime
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let f = test_tokio_spawn();
//await future
f.await;
});
}

// tokio spawn run directly or not ?
async fn test_tokio_spawn() {
println!("test_tokio_spawn !");
tokio::spawn(async {
println!("Hello, world!");
});
}

When you return from main, that causes all backgrounds tasks to get killed. When you use tokio::spawn that creates a background task without waiting for it to execute. The difference in output is whether the background task got to execute before it got killed by exiting from main.

1 Like

thanks !! . I found the tokio::task::spawn at the rust io.crates .There is a sentence in the introduction :The provided future will start running in the background immediately when spawn is called, even if you don’t await the returned JoinHandle . Different results because the main thread exit . thank you !