Skip to content

Instantly share code, notes, and snippets.

@penso
Created June 6, 2023 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save penso/b74cc4d7311b06f2a57b59890635a906 to your computer and use it in GitHub Desktop.
Save penso/b74cc4d7311b06f2a57b59890635a906 to your computer and use it in GitHub Desktop.
How to use tokio + closure parameters
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