Tokio timeout seems not working as the thread hangs up

async fn main_loop() -> Result<()> {
    tokio::select! {
        result = tokio::time::timeout(Duration::from_secs(5), async_cpp_wrapper_fn()) => {
            match result {
                 Ok(r) => r,
                 Err(_) => Err("timeout")
            }
        },
        close_signal => { Ok("shutdown") }
    }
}

async fn async_cpp_wrapper_fn() -> { ... }

I wrapped a cpp logic into an async task, then timeout on it in my application(the main_loop will be spawn onto a reserved thread, but the log print indicated the flow stuck in the wrapper function more than 5s sometimes(up to hours), hard to reproduce. Is there any possible direction to find the cause? Maybe the thread was blocked by cpp?

Putting code in an async fn doesn't mean it will automatically yield. For long-running non-async code, you need to use spawn_blocking() to run it in a way that doesn't interfere with async. And if you're hoping to be able to cancel that long operation — well, that's not possible unless the C++ code provides some way to signal it to stop, or you run it in a subprocess (not a thread).

2 Likes

It sounds like your cpp code is blocking. Please read this article:

2 Likes

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.