Created
June 6, 2023 09:21
-
-
Save penso/b74cc4d7311b06f2a57b59890635a906 to your computer and use it in GitHub Desktop.
How to use tokio + closure parameters
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::Future; | |
use std::sync::Arc; | |
use tokio::sync::Semaphore; | |
use tokio::task::JoinHandle; | |
#[tokio::main] | |
async fn main() -> Result<(), anyhow::Error> { | |
println!("Starting"); | |
first(|count| async move { | |
println!("First: {count}"); | |
Ok(()) | |
}) | |
.await?; | |
Ok(()) | |
} | |
async fn first<F, Fut>(f: F) -> Result<(), anyhow::Error> | |
where | |
F: Fn(usize) -> Fut + Send + Sync + Copy + 'static, | |
Fut: Future<Output = Result<(), anyhow::Error>> + Send + Sync, | |
{ | |
let mut tasks: Vec<JoinHandle<Result<(), anyhow::Error>>> = vec![]; | |
let sem = Arc::new(Semaphore::new(3)); | |
for i in 1..10 { | |
let permit = Arc::clone(&sem).acquire_owned().await?; | |
let task = tokio::spawn(async move { | |
let _permit = permit; | |
f(i).await?; | |
Ok(()) | |
}); | |
tasks.push(task); | |
} | |
futures::future::join_all(tasks).await; | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment