Skip to content

Instantly share code, notes, and snippets.

@monadplus
Created November 16, 2022 21:51
Show Gist options
  • Save monadplus/6a4cbae11315a14de0d29c26b936e418 to your computer and use it in GitHub Desktop.
Save monadplus/6a4cbae11315a14de0d29c26b936e418 to your computer and use it in GitHub Desktop.
Rust: UnorderedFutures
use futures::{stream::FuturesUnordered, StreamExt};
async fn do_something(i: u8) -> String {
format! {"Future {i:#b}"}
}
#[tokio::main]
async fn main() {
let v = std::sync::Arc::new(tokio::sync::Mutex::new(vec![]));
(0..100)
.map(|i| tokio::spawn(do_something(i)))
.collect::<FuturesUnordered<_>>()
.for_each(|r| {
let v = std::sync::Arc::clone(&v);
async move {
let mut lock = v.lock().await;
let str = r.unwrap();
lock.push(str);
}
})
.await;
println!("{v:?}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment