1 Star 0 Fork 1

menuiis / gkit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
errgroup.go 964 Bytes
一键复制 编辑 原始数据 按行查看 历史
menuis 提交于 2024-04-22 10:18 . init
package egroup
import (
"context"
"sync"
"gitee.com/menciis/gkit/goroutine"
)
type Group struct {
ctx context.Context
cancel func()
wg sync.WaitGroup
sync.Once
goroutine goroutine.GGroup
err error
}
func WithContextGroup(ctx context.Context, group goroutine.GGroup) *Group {
g := &Group{}
g.ctx, g.cancel = context.WithCancel(ctx)
g.goroutine = group
return g
}
// WithContext 实例化方法
func WithContext(ctx context.Context) *Group {
g := &Group{}
g.ctx, g.cancel = context.WithCancel(ctx)
g.goroutine = goroutine.NewGoroutine(ctx)
return g
}
// Wait 等待
func (g *Group) Wait() error {
g.wg.Wait()
if g.cancel != nil {
g.cancel()
}
return g.err
}
// Go 异步调用
func (g *Group) Go(f func() error) {
g.wg.Add(1)
g.goroutine.AddTask(func() {
defer g.wg.Done()
if err := f(); err != nil {
g.Do(func() {
// 级联取消
g.err = err
if g.cancel != nil {
g.cancel()
}
})
}
})
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/menciis/gkit.git
git@gitee.com:menciis/gkit.git
menciis
gkit
gkit
4f74120a101e

搜索帮助