即使使用 .await 或 block_on,tokio 中的异步处理也不会完成

问题描述

在以下伪代码中,我使用 async 主函数使用 await 调用异步函数,使用 block_on 调用非异步函数。在这两种情况下,该过程都没有在那个阶段完成。如果可能,我想等待异步函数执行结束不使用 async


async fn asynchronous_ex_fn() -> Arc<Mutex<Vec<T>>> {
    let vec = Arc::new(Mutex::new(Vec::<T>::new()));
    // some .await
    vec
}

#[tokio::main]
async fn main() {
    let vec = asynchronous_ex_fn().await;
    let inner = Arc::try_unwrap(vec).try_inner().unwrap(); // Mutex<blocked
}

fn main() {
    let vec = tokio::runtime::Runtime::new().unwrap().block_on(asynchronous());
    let inner = Arc::try_unwrap(vec).unwrap().into_inner().unwrap();
    // not error but result is not completed ()
    // I was able to get the results of the task underway.
    // For example,if you perform a calculation 3000 times in a for loop 
    // and push the results to vec,only the results of about 300 times are pushed to vec.
}

解决方法

我不确定您的问题是什么,我认为是在异步函数调用中创建向量之前到达了这一行 let inner = Arc::try_unwrap(vec).unwrap().into_inner().unwrap();

我刚刚在操场上复制了你的场景,它正在运行,看看here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...