Skip to main content

Crate compact_waitgroup

Crate compact_waitgroup 

Source
Expand description

A compact asynchronous WaitGroup synchronization primitive.

This crate is designed to be lightweight and executor-agnostic. It works with any async runtime and supports no_std environments (requires alloc).

§Usage

§MonoWaitGroup

use compact_waitgroup::MonoWaitGroup;

let (wg, token) = MonoWaitGroup::new();
assert!(!wg.is_done());

std::thread::spawn(move || {
    // Long-running task
    token.release();
});

// Wait for the task to complete
wg.await;

§WaitGroup

use compact_waitgroup::WaitGroup;

let (wg, factory) = WaitGroup::new();

factory.scope(|token| {
    let token_cloned = token.clone();
    std::thread::spawn(move || {
        // Long-running task
        token_cloned.release();
    });
    std::thread::spawn(move || {
        // Another long-running task
        token.release();
    });
});

// Wait for all tasks to complete
wg.await;

§With async Runtime


use compact_waitgroup::{GroupTokenExt, WaitGroup};

let (wg, factory) = WaitGroup::new();

for (i, token) in std::iter::repeat_n(factory.into_token(), 8).enumerate() {
    let task = async move {
        println!("Task {i} started");
        // Long-running task...
        sleep(std::time::Duration::from_secs(1)).await;
        println!("Task {i} finished");
    };
    spawn(task.release_on_ready(token));
}

// Wait for all tasks to complete
wg.await;

§Memory Layout

This crate is designed to be extremely lightweight. The memory footprint depends on the architecture and the enabled features.

By default, MonoWaitGroup shares the same underlying memory structure as WaitGroup. However, this means MonoWaitGroup carries a usize field for reference counting of workers, which is redundant for the singly-owned MonoGroupToken.

Enabling the compact-mono feature changes the internal definition of MonoWaitGroup. It switches to a dedicated, stripped-down layout that removes the reference counter.

ComponentDefault (64-bit)With compact-monoSaving
WaitGroup32 bytes32 bytes0 bytes
MonoWaitGroup32 bytes24 bytes8 bytes

Structs§

GroupToken
Clonable group token.
GroupTokenFactory
Factory of GroupToken.
GroupTokenReleaseOnDrop
Wrapper that releases a token when the future is dropped.
GroupTokenReleaseOnReady
Wrapper that releases a token when the future is ready or dropped.
MonoGroupToken
Non-clonable group token.
MonoWaitGroup
WaitGroup with a single non-clonable group token.
WaitGroup
WaitGroup with clonable group tokens.

Traits§

GroupTokenExt
Extension trait for futures to automatically release group tokens.
GroupTokenFuncExt
Extension trait for FnOnce to automatically release group tokens.