问题描述
在以下伪代码中,我使用 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。