Last active
March 14, 2024 16:47
-
-
Save corebreaker/ec5f70d5fb8b127b86096be8cb941c7f to your computer and use it in GitHub Desktop.
Rust: How to join_all a dynamic number of async
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
The macro `join!` cannot be used in this context | |
because we need to add any number of asyncs, | |
not known at compile time. | |
Here we provide a list: Vec<FutureWrapper>, | |
and this list is used to call the function `join_all`. | |
Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=eb3732a22a43ada448e35eebbd1e188a | |
*/ | |
extern crate futures; // v0.3.30 | |
use std::{ | |
task::{Context, Poll}, | |
future::Future, | |
pin::Pin | |
}; | |
struct FutureWrapper { | |
future: Pin<Box<dyn Future<Output = ()>>>, | |
} | |
impl FutureWrapper { | |
fn new<F: Future<Output = ()> + 'static>(f: F) -> Self { | |
FutureWrapper { | |
future: Box::pin(f), | |
} | |
} | |
} | |
impl Future for FutureWrapper { | |
type Output = (); | |
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { | |
self.future.as_mut().poll(cx) | |
} | |
} | |
async fn f1() { | |
println!("f1"); | |
} | |
async fn f2() { | |
println!("f2"); | |
} | |
async fn all() { | |
let list = vec![ | |
FutureWrapper::new(f1()), | |
FutureWrapper::new(f2()), | |
]; | |
futures::future::join_all(list).await; | |
} | |
fn main() { | |
futures::executor::block_on(all()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment