golang 携程 errgrou使用

  1. Go团队在实验仓库中添加了一个名为sync.errgroup的新软件包。 sync.ErrGroup再sync.WaitGroup功能的基础上,增加了错误传递,以及在发生不可恢复的错误时取消整个goroutine集合,或者等待超时
  2. Go()方法不仅允许你传一个匿名的函数,而且还能捕获错误信息,你只要像这样返回一个错误 return err,这使开发者使用goroutines时开发效率显著提高
  3. 工具方法封装示例
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package errgroup provides synchronization, error propagation, and Context
// cancelation for groups of goroutines working on subtasks of a common task.
package errgroup

import (
	"context"
	"sync"
)

// A Group is a collection of goroutines working on subtasks that are part of
// the same overall task.
//
// A zero Group is valid and does not cancel on error.
type Group struct {
     
	cancel func()

	wg sync.WaitGroup

	errOnce sync.Once
	err     error
}

// WithContext returns a new Group and an associated Context derived from ctx.
//
// The derived Context is canceled the first time a function passed to Go
// returns a non-nil error or the first time Wait returns, whichever occurs
// first.
func WithContext(ctx context.Context) (*Group, context.Context) {
     
	ctx, cancel := context.WithCancel(ctx)
	return &Group{
     cancel: cancel}, ctx
}

// Wait blocks until all function calls from the Go method have returned, then
// returns the first non-nil error (if any) from them.
func (g *Group) Wait() error {
     
	g.wg.Wait()
	if g.cancel != nil {
     
		g.cancel()
	}
	return g.err
}

// Go calls the given function in a new goroutine.
//
// The first call to return a non-nil error cancels the group; its error will be
// returned by Wait.
func (g *Group) Go(f func() error) {
     
	g.wg.Add(1)

	go func() {
     
		defer g.wg.Done()

		if err := f(); err != nil {
     
			g.errOnce.Do(func() {
     
				g.err = err
				if g.cancel != nil {
     
					g.cancel()
				}
			})
		}
	}()
}

  • 使用示例
	fs := []misc.WorkFunc{
     
		func() error {
     
			tet1()
			return nil
		}, func() error {
     
			tet2()
			return nil
		}, func() error {
     
			tet3()
			return nil
		}, func() error {
     
			tet4()
			return nil
		}, func() error {
     
			tet5()
			return nil
		},
	}
	_ = misc.MultiRun(fs...)
  • 校验是否有协程已发生错误
//校验是否有协程已发生错误
func CheckGoroutineErr(errContext xContext.Context) error {
     
	select {
     
	case <-errContext.Done():
		return errContext.Err()
	default:
		return nil
	}
}


  • 另一个例子
package main
import (
	"fmt"
	"time"
	xContext "golang.org/x/net/context"
	"golang.org/x/sync/errgroup"
)
func main() {
     
	ctx, cancel := xContext.WithCancel(xContext.Background())
	group, errCtx := errgroup.WithContext(ctx)
 
	for index := 0; index < 3; index++ {
     
		indexTemp := index // 子协程中若直接访问index,则可能是同一个变量,所以要用临时变量
 
		// 新建子协程
		group.Go(func() error {
     
			fmt.Printf("indexTemp=%d \n", indexTemp)
			if indexTemp == 0 {
     
				fmt.Println("indexTemp == 0 start ")
				fmt.Println("indexTemp == 0 end")
			} else if indexTemp == 1 {
     
				fmt.Println("indexTemp == 1 start")
				//这里一般都是某个协程发生异常之后,调用cancel()
				//这样别的协程就可以通过errCtx获取到err信息,以便决定是否需要取消后续操作
				cancel()
				fmt.Println("indexTemp == 1 err ")
			} else if indexTemp == 2 {
     
				fmt.Println("indexTemp == 2 begin")
 
				// 休眠1秒,用于捕获子协程2的出错
				time.Sleep(1 * time.Second)
 
				//检查 其他协程已经发生错误,如果已经发生异常,则不再执行下面的代码
				err := CheckGoroutineErr(errCtx)
				if err != nil {
     
					return err
				}
				fmt.Println("indexTemp == 2 end ")
			}
			return nil
		})
	}
 
	// 捕获err
	err := group.Wait()
	if err == nil {
     
		fmt.Println("都完成了")
	} else {
     
		fmt.Printf("get error:%v", err)
	}
}
 
//校验是否有协程已发生错误
func CheckGoroutineErr(errContext xContext.Context) error {
     
	select {
     
	case <-errContext.Done():
		return errContext.Err()
	default:
		return nil
	}
}

你可能感兴趣的:(golang,golang,errgrou)