go errgroup 用法示例
一、demo
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
group.Go(func() error {
fmt.Println("index=%d", indexTemp)
if indexTemp == 0 {
fmt.Println("indexTemp == 0 end ")
} else if indexTemp == 1 {
fmt.Println("indexTemp == 1 start ")
//這裡一般都是某個協程發生異常之後,呼叫cancel()
//這樣別的協程就可以通過errCtx獲取到err資訊,以便決定是否需要取消後續操作
cancel()
fmt.Println("indexTemp == 1 had err ")
} else if indexTemp == 2 {
fmt.Println("indexTemp == 2 begin ")
time.Sleep(1 * time.Second)
//檢查 其他協程已經發生錯誤,如果已經發生異常,則不再執行下面的程式碼
err := CheckGoroutineErr(errCtx)
if err != nil {
return err
}
fmt.Println("indexTemp == 2 end ")
}
return nil
})
}
err := group.Wait()
if err == nil {
fmt.Println("都完成了")
} else {
fmt.Printf("get error:%v\n", err)
}
}
//校驗是否有協程已發生錯誤
func CheckGoroutineErr(errContext xContext.Context) error {
select {
case <-errContext.Done():
return errContext.Err()
default:
return nil
}
}
執行結果如下:
二、errgroup原始碼
// 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 (
"sync"
"golang.org/x/net/context"
)
// 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()
}
})
}
}()
}
個人微信公眾號:
作者:jiankunking 出處:http://blog.csdn.net/jiankunking
相關文章
- Go 併發控制:errgroup 詳解Go
- go中errgroup原始碼解讀Go原始碼
- Go基礎系列:雙層channel用法示例Go
- 八. Go併發程式設計--errGroupGo程式設計
- 十二. Go併發程式設計--sync/errGroupGo程式設計
- 三、Go語言基礎:go build命令用法及示例詳解GoUI
- Go語言基礎(04):go doc命令用法及示例詳解Go
- 從案例中詳解go-errgroup-原始碼Go原始碼
- @Async的用法和示例
- Go示例集合Go
- golang中的errgroupGolang
- Go 中 ...用法Go
- Sass @at-root 指令用法示例
- compare用法示例•選項摘要
- cdMysql?using?用法示例詳解MySql
- go操作elasticsearch示例GoElasticsearch
- Go package time 用法GoPackage
- 騰訊雲上 Selenium 用法示例
- python @pytest.fixture示例及用法Python
- go專案dockerfile示例GoDocker
- Go package(1) time 用法GoPackage
- Go之time包用法Go
- Sanic response stream() 函式用法和示例函式
- Sanic response redirect() 函式用法和示例函式
- Sanic response raw() 函式用法和示例函式
- Sanic response file() 函式用法和示例函式
- Sanic response json() 函式用法和示例JSON函式
- Sanic response html() 函式用法和示例HTML函式
- Sanic response text() 函式用法和示例函式
- Go標準庫:Go template用法詳解Go
- Linux 命令列:find 的 26 個用法示例Linux命令列
- Python常見工廠函式用法示例Python函式
- Go 緩衝通道(bufchan)用法Go
- Go語言之併發示例(Runner)Go
- Sanic response file_stream() 函式用法和示例函式
- 二、Go語言基礎:go install與go fmt命令使用示例詳解Go
- Vue3.4+版本中的 defineModel 宏的用法示例Vue
- 紅寶石async/await用法示例出錯了嗎?AI
- 【go】golang中鎖的用法-互斥鎖Golang