当前位置: > > > > 将 errgroup 嵌套在一堆 goroutine 中
来源:stackoverflow
2024-04-24 17:51:34
0浏览
收藏
亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《将 errgroup 嵌套在一堆 goroutine 中》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。
问题内容
我对 golang 及其并发原则相当陌生。我的用例涉及对一批实体执行多个 http 请求(针对单个实体)。如果某个实体的任何 http 请求失败,我需要停止它的所有并行 http 请求。另外,我必须管理因错误而失败的实体的数量。我正在尝试在实体 goroutine 内实现 errorgroup,这样,如果单个实体的任何 http 请求失败,则 errorgroup 将终止并向其父 goroutine 返回错误。但我不知道如何维护错误计数。
func main(entity[] string) { errorc := make(chan string) // channel to insert failed entity var wg sync.waitgroup for _, link := range entity { wg.add(1) // spawn errorgroup here. errorgroup_spawn } go func() { wg.wait() close(errorc) }() for msg := range errorc { // here storing error entityids somewhere. } }
和这样的错误组
func errorgroup_spawn(ctx context.Context, errorC chan string, wg *sync.WaitGroup) { // and other params defer (*wg).Done() goRoutineCollection, ctxx := errgroup.WithContext(ctx) results := make(chan *result) goRoutineCollection.Go(func() error { // http calls for single entity // if error occurs, push it in errorC, and return Error. return nil }) go func() { goRoutineCollection.Wait() close(result) }() return goRoutineCollection.Wait() }
ps:我也在考虑应用嵌套错误组,但无法在运行其他错误组时维护错误计数 谁能指导我,这是处理此类现实世界场景的正确方法吗?
解决方案
跟踪错误的一种方法是使用状态结构来跟踪哪个错误来自何处:
type status struct { entity string err error } ... errorc := make(chan status) // spawn error groups with name of the entity, and when error happens, push status{entity:entityname,err:err} to the chanel
然后您可以从错误通道读取所有错误并找出失败的原因。
另一个选择是根本不使用错误组。这使得事情更加明确,但是否更好还有待商榷:
// Keep entity statuses statuses:=make([]Status,len(entity)) for i, link := range entity { statuses[i].Entity=link wg.Add(1) go func(i index) { defer wg.Done() ctx, cancel:=context.WithCancel(context.Background()) defer cancel() // Error collector status:=make(chan error) defer close(status) go func() { for st:=range status { if st!=nil { cancel() // Stop all calls // store first error if statuses[i].Err==nil { statuses[i].Err=st } } } }() innerWg:=sync.WaitGroup{} innerWg.Add(1) go func() { defer innerWg.Done() status<- makeHttpCall(ctx) }() innerWg.Add(1) go func() { defer innerWg.Done() status<- makeHttpCall(ctx) }() ... innerWg.Wait() }(i) }
当一切完成后,statuses
将包含所有实体和相应的状态。
今天关于《将 errgroup 嵌套在一堆 goroutine 中》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!