errgroup

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: GPL-3.0 Imports: 4 Imported by: 0

Documentation

Overview

Package errgroup 基于 golang.org/x/sync/errgroup 的源代码基础改进

改进内容: 1. 自动 recover 所有 panic, 并作为 error 抛出

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Group

type Group struct {
	// contains filtered or unexported fields
}

A Group is a collection of goroutines working on subtasks that are part of the same overall task.

A zero Group is valid, has no limit on the number of active goroutines, and does not cancel on error.

Example

忽略任务失败, 所有任务完成才结束, 可以当做 sync.WaitGroup 使用

package main

import (
	"context"

	"github.com/iftechio/go-coco/utils/sync/errgroup"
)

var job = func(ctx context.Context) error { return nil }

func main() {
	ctx := context.Background()
	var g errgroup.Group
	g.Go(func() error {
		return job(ctx)
	})
	g.Go(func() error {
		return job(ctx)
	})
	_ = g.Wait()
}

func New

func New() *Group

New 创建一个新的 Group

func WithContext

func WithContext(ctx context.Context) (*Group, context.Context)

WithContext 将 context 的 cancel 绑定进入 Group, 一旦一个任务发生错误(error/panic), 自动 cancel context

Example

一旦一个任务失败, 自动 cancel 其他任务

package main

import (
	"context"

	"github.com/iftechio/go-coco/utils/sync/errgroup"
)

var job = func(ctx context.Context) error { return nil }

func main() {
	ctx := context.Background()
	g, gctx := errgroup.WithContext(ctx)
	g.Go(func() error {
		return job(gctx)
	})
	g.Go(func() error {
		return job(gctx)
	})
	_ = g.Wait()
}

func (*Group) Go

func (g *Group) Go(f func() error)

Go 启动新的 goroutine 执行任务, 第一个被返回 non-nil error 将作为 Wait 的返回错误

func (*Group) SetLimit

func (g *Group) SetLimit(n int)

SetLimit limits the number of active goroutines in this group to at most n. A negative value indicates no limit.

Any subsequent call to the Go method will block until it can add an active goroutine without exceeding the configured limit.

The limit must not be modified while any goroutines in the group are active.

func (*Group) TryGo

func (g *Group) TryGo(f func() error) bool

TryGo calls the given function in a new goroutine only if the number of active goroutines in the group is currently below the configured limit.

The return value reports whether the goroutine was started.

func (*Group) Wait

func (g *Group) Wait() error

Wait 等待所有任务执行完毕并返回第一个 non-nil error

Jump to

Keyboard shortcuts

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