代码之家  ›  专栏  ›  技术社区  ›  ZeroTerabytes

嵌套for循环中的并发性

  •  1
  • ZeroTerabytes  · 技术社区  · 3 年前

    我正在尝试做一些图像分析,并在Goroutine中分析每个像素。我的代码当前如下所示:

    func FindEdgesV2(img image.Image) PointSet {
        res := make(PointSet)
        c := make(chan Point)
        bounds := img.Bounds()
        width, height := bounds.Max.X, bounds.Max.Y
    
        size := width*height - width*2 - height*2 + 4
        px := 0
        bar := CreateBar(size, "reading pixels...")
        for y := 1; y < height-1; y++ {
            for x := 1; x < width-1; x++ {
    
                go func(x, y int, c chan Point) {
                    gradient := [3][3]int{}
                    for i := 0; i < 3; i++ {
                        for j := 0; j < 3; j++ {
                            gradient[i][j] = int(Luminance(img.At(x-1+i, y-1+i)))
                        }
                    }
    
                    gx, gy := 0, 0
                    for i := 0; i < 3; i++ {
                        for j := 0; j < 3; j++ {
                            gx += gradient[i][j] * horizontal[i][j]
                            gy += gradient[i][j] * vertical[i][j]
                        }
                    }
                    colorCode := int(math.Sqrt(float64(gx*gx + gy*gy)))
                    if colorCode > 80 {
                        c <- Point{x, y}
                    }
                }(x, y, c)
    
                px++
                bar.Set(px)
            }
        }
        for p := range c {
            res[p] = true
        }
        return res
    }
    

    然而,我一直收到这样的错误:

    fatal error: all goroutines are asleep - deadlock!
    

    我只是尝试使用多个Goroutines写入一个频道,然后将该频道的内容放入地图中。我做错了什么?

    1 回复  |  直到 3 年前
        1
  •  1
  •   Burak Serdar    3 年前

    你应该在所有goroutines完成后关闭频道。要做到这一点,您首先必须检测何时使用WaitGroup完成所有goroutine:

    ...
    bar := CreateBar(size, "reading pixels...")
    wg:=sync.WaitGroup{}
    for y := 1; y < height-1; y++ {
       for x := 1; x < width-1; x++ {
            wg.Add(1)
            go func(x, y int, c chan Point) {
               defer wg.Done()
               ...
    

    然后在完成所有gorotines后关闭通道:

    go func() {
        wg.Wait()
        close(c)
    }()
    for p := range c {
        res[p] = true
    }