-
Can we have WaitGroup like feature in tokio? |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 1 reply
-
The standard use-case for WaitGroup in go is to wait for a set of tasks to finish, but the best way to do that in Tokio is to store a let mut join_handles = Vec::new();
for i in 0..10 {
join_handles.push(tokio::spawn(my_async_fn(i)));
}
for jh in join_handles {
jh.await.unwrap();
} You can also use a |
Beta Was this translation helpful? Give feedback.
-
@Darksonn understood! but there could be complex workflow where we want to make sure all tasks are completed. |
Beta Was this translation helpful? Give feedback.
-
There is a library called awaitgroup that might be useful: https://crates.io/crates/awaitgroup I am not the author, but I have used this in the past. Has an interface similar to |
Beta Was this translation helpful? Give feedback.
-
You can also try https://github.com/laizy/waitgroup-rs I made 3 years ago. It is tiny and performant :
|
Beta Was this translation helpful? Give feedback.
-
A newer solution: |
Beta Was this translation helpful? Give feedback.
-
In addition to JoinSet and TaskTracker. we have another way to do it. let (tx, rx) = mpsc::sync_channel::<i32>(1);
for i in 1..=5 {
let tx1 = tx.clone();
spawn(|| {
// ...
drop(tx1)
});
}
drop(tx);
// it will block until all the senders disconnected, then return Err
let _ = rx.recv(); |
Beta Was this translation helpful? Give feedback.
The standard use-case for WaitGroup in go is to wait for a set of tasks to finish, but the best way to do that in Tokio is to store a
Vec<JoinHandle<T>>
and use a loop:You can also use a
JoinSet
instead of the vector.