如何使用WaitGroup处理错误并终止Goroutine [英] How to handle errors and terminate Goroutine using WaitGroup

查看:86
本文介绍了如何使用WaitGroup处理错误并终止Goroutine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天一直在使用Goroutines,Channels和WaitGroup,在阅读了一段时间后,我终于开始理解这个概念。

I have been playing around with Goroutines, Channels and WaitGroup today and I am finally starting to understand the concept, after just been reading about it for a while.

我的问题是我不确定如何以这种方式工作时如何处理错误,主要是因为我使用了WaitGroup。使用WaitGroup时,我首先添加将要执行的goroutine的数量,但是如果其中之一发生错误怎么办?

My problem is that I am unsure how I handle errors when working like this, mainly because of the WaitGroup I use. When using the WaitGroup, I start by adding the amount of goroutines that will be executed, but what if an error happens during one of these?

package main

import (
    "errors"
    "sync"
)

var waitGroup sync.WaitGroup

func main() {
    c := make(chan int, 10)

    waitGroup.Add(10)

    go doSomething(c)

    waitGroup.Wait()
}

func doSomething(c chan int) {
    for i := 0; i < 10; i++ {
        n, err := someFunctionThatCanError()

        if err != nil {
            // How do I end the routines and WaitGroups here?
        }

        c <- n
        waitGroup.Done()
    }

    close(c)    
}

func someFunctionThatCanError() (int, error) {
    return 1, errors.New("an error")
}

游乐场: https:// play。 golang.org/p/ZLsBSqdMD49

我已尽力提供了一个示例来说明我在说什么。循环将在 doSomething()中运行10次,并且每次迭代都会调用 waitGroup.Done(),但是如果在所有这些过程中发生错误,如 someFunctionThatCanError()所示,该怎么办?

I have tried my best to provide an example that shows what I am talking about. A loop will run 10 times in doSomething() and it will call waitGroup.Done() on every iteration, but what if an error happens during all this, like shown with someFunctionThatCanError()?

现在,当我尝试解决问题时,通过返回和/或取消频道,我最终陷入了僵局,因此我不确定从何处去。我也不确定如何处理我认为正在等待更多事情发生的WaitGroup。

When I try to solve it now, by returning and/or cancelling the channel, I end up with deadlocks, so I am a little unsure where to go from here. I am also unsure of how to handel the WaitGroup that I assume is waiting for more things to happen.

任何帮助都非常感谢。

推荐答案

使用 golang。 org / x / sync / errgroup 等待并处理goroutine中的错误。

Use golang.org/x/sync/errgroup to wait on and handle errors from goroutines.

package main

import (
    "errors"
    "log"
    "sync"

    "golang.org/x/sync/errgroup"
)

var waitGroup sync.WaitGroup

func main() {
    c := make(chan int, 10)

    var g errgroup.Group

    g.Go(func() error {
        return doSomething(c)
    })

    // g.Wait waits for all goroutines to complete
    // and returns the first non-nil error returned
    // by one of the goroutines.
    if err := g.Wait(); err != nil {
        log.Fatal(err)
    }
}

func doSomething(c chan int) error {
    defer close(c)
    for i := 0; i < 10; i++ {
        n, err := someFunctionThatCanError()
        if err != nil {
            return err
        }
        c <- n
    }
    return nil
}

func someFunctionThatCanError() (int, error) {
    return 1, errors.New("an error")
}

在操场上运行

这篇关于如何使用WaitGroup处理错误并终止Goroutine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆