golang改进errGroup,实现并发超时控制
需求
在并发控制中,想实现以下功能
1、并发超时控制
2、一个出错,主程序退出
3、兼容errGroup
然后对errGroup进行一次改写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 | package utils import ( "context" "errors" "fmt" "sync" "time" ) type token struct {} // 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. type Group struct { cancel func () wg sync.WaitGroup sem chan token errOnce sync.Once err error unsafe bool ctx context.Context } var errTimeout = errors.New( "超时了" ) func (g *Group) done() { if g.sem != nil { <-g.sem } g.wg.Done() } // 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, unsafe: true, ctx: ctx}, ctx } // GroupTimeoutContext 超时设置 func GroupTimeoutContext(parent context.Context, timeout time.Duration) (*Group, context.Context) { ctx, cancel := context.WithTimeout(parent, timeout) return &Group{cancel: cancel, unsafe: true, ctx: ctx}, ctx } // 超时设置 func GroupTimeout(parent context.Context, timeout time.Duration) *Group { ctx, cancel := context.WithTimeout(parent, timeout) return &Group{cancel: cancel, unsafe: true, ctx: ctx} } // UnsafeGroup 获取不安全的同步锁(出错就退出) func UnsafeGroup() *Group { var g Group g.unsafe = true g.ctx, g.cancel = context.WithCancel(context.Background()) return &g } // 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 { if g.unsafe { monitor := make( chan struct {}) go func () { g.wg.Wait() close(monitor) }() select { case <-g.ctx.Done(): g.errOnce.Do( func () { if nil == g.err { g.err = errTimeout } }) case <-monitor: } } else { g.wg.Wait() } if g.cancel != nil { g.cancel() } return g.err } // Go calls the given function in a new goroutine. // It blocks until the new goroutine can be added without the number of // active goroutines in the group exceeding the configured limit. // // 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 () (err error)) { if g.sem != nil { g.sem <- token{} } if g.unsafe && g.cancel == nil { g.ctx, g.cancel = context.WithCancel(context.Background()) } g.wg.Add(1) go func () { defer g.done() if err := f(); err != nil { g.errOnce.Do( func () { if nil == g.err { g.err = err } if g.cancel != nil { g.cancel() } }) } }() } // 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 (g *Group) TryGo(f func () error) bool { if g.sem != nil { select { case g.sem <- token{}: // Note: this allows barging iff channels in general allow barging. default : return false } } if g.unsafe && g.cancel == nil { g.ctx, g.cancel = context.WithCancel(context.Background()) } g.wg.Add(1) go func () { defer g.done() if err := f(); err != nil { g.errOnce.Do( func () { if nil == g.err { g.err = err } if g.cancel != nil { g.cancel() } }) } }() return true } // 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 (g *Group) SetLimit(n int) { if n < 0 { g.sem = nil return } if len(g.sem) != 0 { panic(fmt.Errorf( "errgroup: modify limit while %v goroutines in the group are still active" , len(g.sem))) } g.sem = make( chan token, n) } // IsErr 判断是否执行出错 func (g *Group) IsErr(err error, message ... interface {}) bool { // 有错误直接返回 if g.err != nil { return true } // 无错误直接返回 if err == nil { return false } switch len(message) { case 0: g.errOnce.Do( func () { if nil == g.err { g.err = err } if g.cancel != nil { g.cancel() } }) case 1: g.errOnce.Do( func () { if nil == g.err { g.err = fmt.Errorf( "%v:%w" , message[0], err) } if g.cancel != nil { g.cancel() } }) default : // 格式化输出 g.errOnce.Do( func () { if nil == g.err { s, _ := message[0].(string) g.err = fmt.Errorf( "%s:%w" , fmt.Sprintf(s, message[1:]...), err) } if g.cancel != nil { g.cancel() } }) } return true } func IsTimeout(err error) bool { if err == nil { return false } return errors.Is(err, errTimeout) } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人