登录
首页 >  Golang >  Go问答

惯用的 goroutine 并发和错误处理

来源:stackoverflow

时间:2024-04-12 12:12:36 105浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《惯用的 goroutine 并发和错误处理》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

在下面的代码块中,我尝试运行多个例程并获取所有例程的结果(无论成功还是错误)。

package main
    
    import (
        "fmt"
        "sync"
    )
    
    func processbatch(num int, errchan chan<- error, resultchan chan<- int, wg *sync.waitgroup) {
        defer wg.done()
    
        if num == 3 {
            resultchan <- 0
            errchan <- fmt.errorf("goroutine %d's error returned", num)
        } else {
            square := num * num
    
            resultchan <- square
    
            errchan <- nil
        }
    
    }
    
    func main() {
        var wg sync.waitgroup
    
        batches := [5]int{1, 2, 3, 4, 5}
    
        resultchan := make(chan int)
        errchan := make(chan error)
    
        for i := range batches {
            wg.add(1)
            go processbatch(batches[i], errchan, resultchan, &wg)
        }
    
        var results [5]int
        var err [5]error
        for i := range batches {
            results[i] = <-resultchan
            err[i] = <-errchan
        }
        wg.wait()
        close(resultchan)
        close(errchan)
        fmt.println(results)
        fmt.println(err)
    }

演示:https://go.dev/play/p/za-py9gdjce 这段代码有效,我得到了我想要的结果,即:

[25 1 4 0 16]
[   goroutine 3's error returned ]

我想知道是否有更惯用的方法来实现这一目标。我浏览了 errgroup 包:https://pkg.go.dev/golang.org/x/sync/errgroup 但无法找到可以帮助我的东西。欢迎提出任何建议。


正确答案


在此代码中,waitgroup 是多余的。执行与等待通道结果的循环完全同步。在所有函数完成其工作并从通道读取发布的结果之前,代码不会继续前进。 仅当您的函数需要在结果发布到渠道后执行任何工作时,才需要等待组。

我也更喜欢稍微不同的实现。在发布的实现中,每次执行函数时,我们不会将结果和错误都发送到通道中。相反,我们可以仅发送成功执行的结果,并在代码失败时仅发送错误。

优点是简化结果/错误处理。我们在没有 nils 的情况下获得了结果和错误的片段。

在此示例中,函数返回一个数字,如果出现错误,我们将发送其默认值 0。如果零可能是合法的函数执行结果,那么从成功中过滤掉不成功的执行结果可能会很复杂。

与错误相同。要检查是否有任何错误,我们可以使用简单的代码,例如 if len(errs) != 0

package main

import (
    "fmt"
)

func processbatch(num int, errchan chan<- error, resultchan chan<- int) {
    if num == 3 {
        // no need to send result when it is meanenless
        // resultchan <- 0
        errchan <- fmt.errorf("goroutine %d's error returned", num)
    } else {
        square := num * num

        resultchan <- square

        // no need to send errror when it is nil
        // errchan <- nil
    }

}

func main() {
    batches := [5]int{1, 2, 3, 4, 5}

    resultchan := make(chan int)
    errchan := make(chan error)

    for i := range batches {
        go processbatch(batches[i], errchan, resultchan)
    }

    // use slices instead of arrays because legth varry now
    var results []int
    var errs []error

    // every time function executes it sends singe piece of data to one of two channels
    for range batches {
        select {
        case res := <-resultchan:
            results = append(results, res)
        case err := <-errchan:
            errs = append(errs, err)
        }
    }

    close(resultchan)
    close(errchan)

    fmt.println(results)
    fmt.println(errs)
}

https://go.dev/play/p/SYmfl8iGxgD

[25 1 16 4]
[goroutine 3's error returned]

如果可以使用外部软件包,我们可以从一些 multierr 软件包中受益。例如,github.com/hashicorp/go-multierror

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>