微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决即使使用 .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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。