Created
November 16, 2022 21:51
-
-
Save monadplus/6a4cbae11315a14de0d29c26b936e418 to your computer and use it in GitHub Desktop.
Rust: UnorderedFutures
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
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