听说今天是中元节~~~~~~,该节是追怀先人的一种文化传统节日,其文化核心是敬祖尽孝,并不是鬼节。
学习以下errgroup。
errgroup位于golang.org/x/sync,也是golang官方扩展包下。他的功能类似于理解sync.WaitGroup,都会阻塞等待直到所有相关goroutine执行完毕。
其区别就像他的名字一样,errgroup封装了error的处理,帮助开发人员更友好的处理相关goroutine中出现的error。
结构
1 | type Group struct { |
- cancel 这里保存的是contex.WithCancel返回的第二个参数。取消函数,主要来包装context.WithCancel的CancelFunc
- wg 借助于WaitGroup实现的,可以等待所有go程结束参见理解sync.WaitGroup
- errOnce 使用sync.Once实现只输出第一个err参见sync.Once
- err 保存第一个错误
代码结构
1 |
|
整个errgroup的结构及其简单,仅提供了3个方法。使用起来也及其简单。
- WithContext(ctx context.Context) (*Group, context.Context)
- Wait() error
- Go(f func() error)
func WithContext(ctx context.Context) (*Group, context.Context)
1 | func WithContext(ctx context.Context) (*Group, context.Context) { |
WithContext返回一个新的Group和一个从ctx派生的相关Context。派生的上下文在传递给Go()第一次出现非零错误或Wait第一次返回时被取消。传递给 Go 的函数第一次返回非零错误时,或 Wait 第一次返回时,以先发生者为准。 第一次。
func (g *Group) Wait() error
1 | func (g *Group) Wait() error { |
利用WaitGroup阻塞等待,直到所有来自Go()方法的函数调用都返回,然后返回其中第一个非nil的错误(如果有的话)。
func (g *Group) Go(f func() error)
1 | func (g *Group) Go(f func() error) { |
入参为仅有error返回值的func(),Go()在一个新的goroutine中调用给定的函数。利用once的特点收集第一个获得到的error。
第一个返回非nil错误的调用将取消该组;其错误将被Wait()返回。