Expand description
This library provides facility to wait on multiple spawned async tasks. It is runtime agnostic.
§Adding and waiting on tasks
use taskwait::TaskGroup;
#[tokio::main]
async fn main() {
let tg = TaskGroup::new();
for _ in 0..10 {
tg.add();
let tg_c = tg.clone();
tokio::spawn(async move{
//...
tg_c.done();
});
}
tg.wait().await;
}
Note: User must ensure that call to done() made above is made in both success & error code path.
§Using add_work
This example uses add_work() which creates a Work
object. When it goes out of scope done() is
is automatically called.
use taskwait::TaskGroup;
#[tokio::main]
async fn main() {
let tg = TaskGroup::new();
for _ in 0..10 {
let work = tg.add_work(1);
tokio::spawn(async move{
let _work = work; // done() will be called when this is dropped
//...
});
}
tg.wait().await;
}
§Reusing the taskgroup
The following shows how the same task group can be reused to achieve checkpointing
use taskwait::{TaskGroup, Work};
async fn multiple_tasks(tg: TaskGroup, count: usize) {
for _ in 0..count {
let work = tg.add_work(1);
tokio::spawn(async move {
let _work = work;
// .. do something
});
}
}
#[tokio::main]
async fn main() {
let tg = TaskGroup::new();
// Spawn 100 tasks
tokio::spawn(multiple_tasks(tg.clone(), 100));
// Let the first 100 complete first.
tg.wait().await;
// Spawn 2nd batch
tokio::spawn(multiple_tasks(tg.clone(), 100));
// Now wait for 2nd batch
tg.wait().await; // Wait for the next 100
}
Structs§
- Task
Group - Group of tasks to be waited on.
- Wait
Future - Future to wait for the counter to become 0 or -ve.
- Work
- Represents a work or task.