[tokio] Why is my inner task acting like it's been awaited?

Why does inner_task run at all when nothing calls .await on it? I'm assuming it's because .await was called on the outer task, but I can't find any relevant docs explaining what is happening.

use tokio;

async fn test() {
    println!("Hello from test");
}

#[tokio::main]
async fn main() {

    let (tx, mut rx) = tokio::sync::mpsc::channel(32);
    
    let task = tokio::task::spawn(async move {
        println!("Hello from outer task");
        let inner_task = tokio::task::spawn(async move {
            println!("Hello from inner task");
        });
        println!("Outer task sending inner task");
        tx.send(inner_task).await.unwrap();
        println!("Goodbye from outer task");
    });
    
    println!("Have not awaited task yet");
    
    let t = test();
    println!("Have not awaited test yet");
    t.await;
    println!("Test was awaited");
    
    println!("Outer task not yet awaited");
    task.await;
    println!("Outer task was awaited");
    while let Some(t) = rx.recv().await {
        println!("not awaiting inner task");
    }
}

(Playground)

Output:

Have not awaited task yet
Have not awaited test yet
Hello from test
Test was awaited
Outer task not yet awaited
Hello from outer task
Outer task sending inner task
Goodbye from outer task
Outer task was awaited
not awaiting inner task
Hello from inner task

Because that's what tokio::spawn does. Make the task start immediately.

1 Like

That seems obvious in retrospect. I guess I thought that since JoinHandle implements Future you had to await it to start execution.

Thank you!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.