登录
首页 >  Golang >  Go问答

为什么我的函数没有正确等待 goroutine 的执行?

来源:stackoverflow

时间:2024-02-09 19:09:25 444浏览 收藏

哈喽!大家好,很高兴又见面了,我是golang学习网的一名作者,今天由我给大家带来一篇《为什么我的函数没有正确等待 goroutine 的执行?》,本文主要会讲到等等知识点,希望大家一起学习进步,也欢迎大家关注、点赞、收藏、转发! 下面就一起来看看吧!

问题内容

我有一个函数,它发出一个 get 请求,然后将响应和编码后的响应存储在一个结构中。它接受一个指向等待组的指针

这是该函数

type encodeddata string

type encodedimage struct {
    data        []byte
    encodeddata encodeddata
    error       error
}

func getpainting(url string, ei *encodedimage, wg *sync.waitgroup) {
    defer wg.done()

    res, err := http.get(url)
    if err != nil {
        ei.error = errors.wrapf(err, "unable to fetch from provided url %s", url)
    }

    body, err := ioutil.readall(res.body)
    if err != nil {
        ei.error = err
    }

    encoded := b64.stdencoding.encodetostring(body)
    ei.data, ei.encodeddata = body, encodeddata(encoded)
}

这是调用前一个函数的函数。它是 gin 路由器的处理程序。

func Search(db *gorm.DB) gin.HandlerFunc {
    return func(c *gin.Context) {
        
        // this is just receiving a search term, making a query, and then loading it into "results". 
        term := c.Param("term")
        var results []models.Searches
        db.Table("searches").Where("to_tsvector(\"searches\".\"Title\" || '' || \"searches\".\"Artist_Name\") @@ plainto_tsquery(?)", term).Find(&results)

        
        var wg sync.WaitGroup

        // results is an slice of structs
        for i, re := range results {

            var ed EncodedImage
            wg.Add(1)

            // here is the function defined above
            go GetPainting(re.IMG, &ed, &wg)
            if ed.Error != nil {
                c.JSON(http.StatusInternalServerError, ed.Error.Error())
                panic(ed.Error)
            }

            results[i].IMG = fmt.Sprintf("data:image/jpeg;base64,%v", ed.EncodedData)
        }

        wg.Wait()
        c.JSON(http.StatusOK, results)
}

json 响应显示“data:image/jpeg;base64”,这意味着 goroutine 不会等待完成

这一切都可以在不使用额外 goroutine 的情况下工作。换句话说,当我引入 go 关键字时,事情就停止了。我想尝试这个来加快速度。非常感谢任何见解或建议!


正确答案


问题在这里:

go getpainting(re.img, &ed, &wg) // goroutine alters ed
...
results[i].img = fmt.sprintf("data:image/jpeg;base64,%v", ed.encodeddata)

go 语句作为独立的并发控制线程启动函数调用的执行...”(source);您不应该假设 goroutine 何时执行任何操作。那么可能发生的情况(我还没有具体了解 goroutine 目前是如何管理的)是这样的:

  1. go getpainting(re.img, &ed, &wg) - 运行时安排 getpainting 运行。
  2. results[i].img = fmt.sprintf("data:image/jpeg;base64,%v", ed.encodeddata) 运行(ed.endodeddata 仍然是 nil)。
  3. getpainting 运行。

您已经创建了data race;也就是说,您有一个 goroutine 写入 ed.encodeddata ,而另一个 goroutine 则在没有同步的情况下从中读取。一般来说,很难预测比赛时会发生什么;但在这种情况下,你的 goroutine 正在执行 io (http.get),因此很可能写入会在读取之后发生。

为了帮助解释这一点(以及潜在的解决方案),让我们简化您的示例 (playground):

func routine(wg *sync.waitgroup, val *int) {
    defer wg.done()
    time.sleep(time.microsecond)
    *val = rand.int()
}

func main() {
    const iterations = 5
    var wg sync.waitgroup
    wg.add(iterations)
    r := make([]int, iterations)
    results := make([]string, iterations)
    for i := 0; i < 5; i++ {
        go routine(&wg, &r[i])
        results[i] = fmt.sprintf("data:image/jpeg;base64,%d", r[i])
    }
    wg.wait()
    for i := 0; i < 5; i++ {
        fmt.println(r[i], results[i])
    }
}

正如您在 waitgroup 完成后看到的那样,r(类似于您的 ed)已填充,但 results 包含所有 0 值。这指向一个简单的解决方案(playground):

for i := 0; i < 5; i++ {
    go routine(&wg, &r[i])
}
wg.wait()
results := make([]string, iterations)
for i := 0; i < 5; i++ {
    results[i] = fmt.sprintf("data:image/jpeg;base64,%d", r[i])
}
for i := 0; i < 5; i++ {
    fmt.println(r[i], results[i])
}

这是有效的,因为在知道 goroutine 完成之前(通过 waitgroup),您不会访问它们写入的任何内容。将此方法转移到您的代码中相当简单(创建 utils.encodedimage 的切片并在 wg.wait() 之后检查错误/结果)。

虽然上述方法有效,但在所有 goroutine 完成之前它永远不会完成。这通常是不可取的,例如,如果收到一个错误是致命的,那么您可能希望在收到错误后立即向用户返回响应(并停止任何正在进行的工作)。

有多种方法可以解决这个问题。将函数传递给 context 是一种非常常见的方法,可以让您在函数应该停止时发出信号(有关您的用例,请参阅 NewRequestWithContext)。在处理响应时,您可以自己编写代码(但很容易 leak goroutines)或使用类似 golang.org/x/sync/errgroup 的内容。这是一个示例(playground):

func routine(ctx context.context, val *int) error {
    select {
    case <-time.after(time.microsecond * time.duration(rand.intn(20))): // select will exit after a number of milliseconds
    case <-ctx.done(): // unless this is met (operation cancelled)
        fmt.println("goroutine ending due to context")
        return ctx.err()
    }
    *val = rand.int()
    fmt.println("generated ", *val)
    if simulateerrors && *val > (math.maxint/2) {
        return errors.new("number too big")
    }
    return nil
}

func main() {
    const iterations = 5
    // in your case source context should probably come from gin.context so the operation is cancelled if the connection drops
    g, ctx := errgroup.withcontext(context.background())
    r := make([]int, iterations)
    for i := 0; i < iterations; i++ {
        x := &r[i]
        g.go(func() error {
            return routine(ctx, x)
        })
    }
    if err := g.wait(); err != nil {
        fmt.println("got an error!", err)
        return // here you send error as response (you might want to send something generic to avoid leaking system detail)
    }
    // everything has processed ok
    results := make([]string, iterations)
    for i := 0; i < iterations; i++ {
        results[i] = fmt.sprintf("data:image/jpeg;base64,%d", r[i])
        fmt.println(r[i], results[i])
    }
}

注意:在生产代码中使用 panic 时要小心。在您的示例中,当 http get 失败时,您将执行此操作;这种情况很可能在某个时刻发生,并且您确实不希望应用程序关闭(如果发生的话)(向最终用户返回一个明智的错误,并可能记录失败)。捕获恐慌是可能的,但通常最好在检测到错误时进行处理。

@Brits 在上面的评论中给出了正确的答案。在 goroutine 中设置 results[i].img 是正确的解决方案。我还添加了他建议的错误处理。下面是更新后的代码,供需要的人使用:

注意:我将 getpainting 设为 encodedimage 的方法,以便在调用它时提高可读性。它返回 errgroup.group.go() 的错误

func (ei *encodedimage) getpainting(url string, wg *sync.waitgroup, result *models.searches) error {
    defer wg.done()

    res, err := http.get(url)
    if err != nil {
        return err
    }

    body, err := ioutil.readall(res.body)
    if err != nil {
        return err
    }

    encoded := b64.stdencoding.encodetostring(body)
    ei.data, ei.encodeddata = body, encodeddata(encoded)

    result.img = fmt.sprintf("data:image/jpeg;base64,%v", ei.encodeddata)
    
    return nil
}
func Search(db *gorm.DB) gin.HandlerFunc {
    return func(c *gin.Context) {
        term := c.Param("term")
        var results []models.Searches
        db.Table("searches").Where("to_tsvector(\"searches\".\"Title\" || '' || \"searches\".\"Artist_Name\") @@ plainto_tsquery(?)", term).Find(&results)

        var wg sync.WaitGroup
        var g errgroup.Group

        for i, re := range results {

            var ed utils.EncodedImage
            wg.Add(1)

            g.Go(ed.GetPainting(re.IMG, &wg, &results[i]))
            if err := g.Wait(); err != nil {
                c.JSON(http.StatusInternalServerError, err.Error())
                panic(err)
            }
        }

        g.Wait()
        c.JSON(http.StatusOK, results)
    }
}

今天关于《为什么我的函数没有正确等待 goroutine 的执行?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

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