Struct wg::AsyncWaitGroup
source · [−]pub struct AsyncWaitGroup { /* private fields */ }Expand description
An AsyncWaitGroup waits for a collection of threads to finish.
The main thread calls add to set the number of
thread to wait for. Then each of the goroutines
runs and calls Done when finished. At the same time,
Wait can be used to block until all goroutines have finished.
A WaitGroup must not be copied after first use.
Example
use wg::AsyncWaitGroup;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::{spawn, time::{sleep, Duration}};
#[tokio::main(flavor = "multi_thread", worker_threads = 10)]
async fn main() {
let wg = AsyncWaitGroup::new();
let ctr = Arc::new(AtomicUsize::new(0));
for _ in 0..5 {
let ctrx = ctr.clone();
let t_wg = wg.add(1);
spawn(async move {
// mock some time consuming task
sleep(Duration::from_millis(50)).await;
ctrx.fetch_add(1, Ordering::Relaxed);
// mock task is finished
t_wg.done();
});
}
wg.wait().await;
assert_eq!(ctr.load(Ordering::Relaxed), 5);
}Implementations
sourceimpl AsyncWaitGroup
impl AsyncWaitGroup
sourcepub fn add(&self, num: usize) -> Self
pub fn add(&self, num: usize) -> Self
Adds delta to the WaitGroup counter.
If the counter becomes zero, all threads blocked on wait are released.
Note that calls with a delta that occur when the counter is zero
must happen before a Wait.
Typically this means the calls to add should execute before the statement
creating the thread or other event to be waited for.
If a AsyncWaitGroup is reused to wait for several independent sets of events,
new add calls must happen after all previous wait calls have returned.
Example
use wg::AsyncWaitGroup;
#[tokio::main(flavor = "multi_thread", worker_threads = 10)]
async fn main() {
let wg = AsyncWaitGroup::new();
wg.add(3);
(0..3).for_each(|_| {
let t_wg = wg.clone();
tokio::spawn(async move {
// do some time consuming work
t_wg.done();
});
});
wg.wait().await;
}sourcepub fn done(&self)
pub fn done(&self)
done decrements the WaitGroup counter by one.
Example
use wg::AsyncWaitGroup;
#[tokio::main(flavor = "multi_thread", worker_threads = 10)]
async fn main() {
let wg = AsyncWaitGroup::new();
wg.add(1);
let t_wg = wg.clone();
tokio::spawn(async move {
// do some time consuming task
t_wg.done();
});
}sourcepub async fn wait(&self)
pub async fn wait(&self)
wait blocks until the WaitGroup counter is zero.
Example
use wg::AsyncWaitGroup;
#[tokio::main(flavor = "multi_thread", worker_threads = 10)]
async fn main() {
let wg = AsyncWaitGroup::new();
wg.add(1);
let t_wg = wg.clone();
tokio::spawn( async move {
// do some time consuming task
t_wg.done()
});
// wait other thread completes
wg.wait().await;
}