Is async func interrupted after tokio:time:timeout

I have question about timeout in async workflow.

use std::time::Duration;
use tokio::time::timeout;

#[tokio::main]
async fn main() {
    let operation = async_operation();
    let result = timeout(Duration::from_secs(5), operation).await;

    match result {
        Ok(value) => {
            println!("Operation completed: {:?}", value);
        }
        Err(err) => {
            eprintln!("Operation timed out or encountered an error: {:?}", err);
        }
    }
}

async fn async_operation() -> u32 {
    // Simulate a long-running operation
    tokio::time::sleep(Duration::from_secs(10)).await;

    42
}

In the above example, the result is Operation timed out or encountered an error: Elapsed(()). I am curious that is async_operation shut down after the timeout future is polled, or async_operation is keep doing but the result is ignored when polled. I also tried adding the loop in async_operation, and this code is ends with the timeout::err, so it seems to me that async_operation is interrupted after timeout. But, where and when does the interruption occur? I did not find any related interruption or signal in src/tokio/time/timeout.rs. Does anyone know how timeout works internally?

You're consuming the ownership of the future in timeout, so the future is dropped.

If you want to keep the future around, pin the future to use &mut instead. Rust Playground

#[tokio::main]
async fn main() {
    let mut operation = pin!(async_operation());
    let now = Instant::now();
    loop {
        let result = timeout(Duration::from_secs(1), &mut operation).await;

        match result {
            Ok(value) => {
                println!("Operation completed: {:?}", value);
                return;
            }
            Err(err) => {
                eprintln!("Operation timed out or encountered an error: {:?}", err);
            }
        }
        println!("{}s", now.elapsed().as_secs());
    }
}

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.