#concurrency #tasks #construct #child #structured #spawn #wait

spawn_groups

Structured concurrency construct written in Rust, for Rustaceans

1 stable release

1.0.0 Sep 24, 2023
0.1.1 Sep 24, 2023
0.1.0 Sep 24, 2023

#667 in Asynchronous

Download history 19/week @ 2024-02-25 5/week @ 2024-03-10 77/week @ 2024-03-24 32/week @ 2024-03-31

114 downloads per month

Custom license

57KB
1K SLoC

spawn_groups

rustc crate github license

Introduction

A structured concurrency construct which provides a way to spawn and run an arbitrary number of child tasks, possibly await the results of each child task immediately after it has finish executing, cancel all running child tasks or wait for all child tasks to finish their execution. This was heavily influenced by the Swift language's TaskGroup.

Installation

Add to your code


$ cargo add spawn_groups

Example

use async_std::io::{self};
use async_std::net::{TcpListener, TcpStream};
use async_std::prelude::*;
use spawn_groups::{with_err_spawn_group, GetType, Priority};

async fn process(stream: TcpStream) -> io::Result<()> {
    println!("Accepted from local: {}", stream.local_addr()?);
    println!("Accepted from: {}", stream.peer_addr()?);
    let mut reader = stream.clone();
    let mut writer = stream;
    io::copy(&mut reader, &mut writer).await?;
    Ok(())
}

type Void = ();

#[async_std::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;
    println!("Listening on {}", listener.local_addr()?);
    with_err_spawn_group(Void::TYPE, io::Error::TYPE, |mut group| async move {
        let mut incoming = listener.incoming();
        while let Some(stream) = incoming.next().await {
            let Ok(stream) = stream else {
                return Err(stream.expect_err("Expected an error"));
            };
            group.spawn_task(Priority::default(), async move { process(stream).await });
        }
        Ok(())
    })
    .await?;

    Ok(())
}

Documentation

For a better documentation of this rust crate. Visit here

Dependencies

~1.2–8MB
~39K SLoC