wg-0.7.2 has been yanked.
Golang like WaitGroup implementation for sync/async Rust.
Introduction
By default, blocking version WaitGroup is enabled.
If you are using tokio, you need to enable tokio feature in your Cargo.toml and use wg::tokio::AsyncWaitGroup.
If you are using other async runtime, you need to
enbale future feature in your Cargo.toml and use wg::future::AsyncWaitGroup.
Sync
[dependencies]
wg = "0.7"
tokio
An async implementation for tokio runtime.
[dependencies]
wg = { version: "0.7", features = ["tokio"] }
future
A more generic async implementation.
[dependencies]
wg = { version: "0.7", features = ["future"] }
Instruction
Sync
use wg::WaitGroup;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use std::thread::{spawn, sleep};
fn main() {
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 || {
sleep(Duration::from_millis(50));
ctrx.fetch_add(1, Ordering::Relaxed);
t_wg.done();
});
}
wg.wait();
assert_eq!(ctr.load(Ordering::Relaxed), 5);
}
tokio
use wg::tokio::AsyncWaitGroup;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio::{spawn, time::{sleep, Duration}};
#[tokio::main]
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 {
sleep(Duration::from_millis(50)).await;
ctrx.fetch_add(1, Ordering::Relaxed);
t_wg.done();
});
}
wg.wait().await;
assert_eq!(ctr.load(Ordering::Relaxed), 5);
}
async-io
use wg::future::AsyncWaitGroup;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use async_std::task::{spawn, block_on, sleep};
fn main() {
block_on(async {
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 {
sleep(Duration::from_millis(50)).await;
ctrx.fetch_add(1, Ordering::Relaxed);
t_wg.done();
});
}
wg.wait().await;
assert_eq!(ctr.load(Ordering::Relaxed), 5);
});
}
Acknowledgements
License