asyncutil

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2021 License: MIT Imports: 2 Imported by: 1

README

asyncutil

Go Reference Go Report Card

A collection of utilities for concurrent programming in Go.

Usage

godoc

Collect
func someWork(id int) chan error {
    errs := make(chan error)
    go func(result *Result) {
        // ...
        errs <- err
    }(&Result{ID: id})
    return errs
}

for err := range asyncutil.Collect(
    someWork(1),
    someWork(2),
) {
    if err != nil {
        fmt.Println("Error:", err)
    }
}

Benchmarks

$ go test -bench . -count 1 .
goos: darwin
goarch: amd64
pkg: github.com/sanggonlee/asyncutil
Collect

5 functions running, each taking 50 milliseconds:

BenchmarkCollect_5_functions_of_50_milliseconds_each-8                21          52155152 ns/op
BenchmarkSequential_5_functions_of_50_milliseconds_each-8              4         262524126 ns/op

2 functions running, each taking 30 milliseconds:

BenchmarkCollect_2_functions_of_30_milliseconds_each-8                38          32424379 ns/op
BenchmarkSequential_2_functions_of_30_milliseconds_each-8             18          64462037 ns/op

5 functions running, each taking 200 milliseconds:

BenchmarkCollect_5_functions_of_200_milliseconds_each-8                5         202613911 ns/op
BenchmarkSequential_5_functions_of_200_milliseconds_each-8             1        1012167372 ns/op

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Collect

func Collect(errchans ...<-chan error) <-chan error

Collect takes error channels and returns a new error channel where all non-nil errors from input error channels are funneled into.

Example
package main

import (
	"fmt"
	"net/http"

	"github.com/sanggonlee/asyncutil"
)

func main() {
	doWork := func(url string) chan error {
		errs := make(chan error)
		go func(url string) {
			// Some expensive work..
			_, err := http.Get(url)
			if err != nil {
				errs <- err
			}
		}(url)
		return errs
	}

	for err := range asyncutil.Collect(
		doWork("1"),
		doWork("2"),
	) {
		if err != nil {
			fmt.Println("Error:", err)
		}
	}
}

func CollectContext

func CollectContext(ctx context.Context, errchans ...<-chan error) <-chan error

CollectContext is same as Collect, except it takes a context. If the context exceeds deadline or is cancelled, the resulting error channel receives the corresponding error, in addition to the errors collected by errchans. If the context was already cancelled by the time CollectContext is executed, the resulting error channel will only contain the context error, and not the errors collected by errchans.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL