pub struct WaitGroup { /* private fields */ }std only.Expand description
A WaitGroup 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::WaitGroup;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use std::thread::{spawn, sleep};
let wg = WaitGroup::new();
let ctr = Arc::new(AtomicUsize::new(0));
for _ in 0..5 {
let ctrx = ctr.clone();
let t_wg = wg.add(1);
spawn(move || {
// mock some time consuming task
sleep(Duration::from_millis(50));
ctrx.fetch_add(1, Ordering::Relaxed);
// mock task is finished
t_wg.done();
});
}
wg.wait();
assert_eq!(ctr.load(Ordering::Relaxed), 5);Implementations§
source§impl WaitGroup
impl WaitGroup
sourcepub fn new() -> Self
pub fn new() -> Self
Creates a new wait group and returns the single reference to it.
§Examples
use wg::WaitGroup;
let wg = WaitGroup::new();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 WaitGroup 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::WaitGroup;
let wg = WaitGroup::new();
wg.add(3);
(0..3).for_each(|_| {
let t_wg = wg.clone();
std::thread::spawn(move || {
// do some time consuming work
t_wg.done();
});
});
wg.wait();