douzhizao0270 2017-07-15 08:37
浏览 35
已采纳

go中的例程和通道

I'm trying to run a few calculations in parallel using Go's concurrency:

func intensity_calc(input Matrix, distance float64) Matrix {
    output := create_matrix(len(input), len(input[0]))
    var wg sync.WaitGroup
    reverse := len(input)

    wg.Add(len(input) / 2)
    for i := 0; i < len(input)/2; i++ {
        output[i][x_ln] = input[i][x_ln]
        go func() { // creates a go-routine
        points <- contributions_sum(input, distance, input[i][x_ln])
        output[i][y_ln] = <-points
        output[reverse][y_ln] = output[i][y_ln]
        fmt.Println(i)
        defer wg.Done() // process is done
    }()
    }
    wg.Wait() // wait until all processes are finished
    return output
}

* output is a 2D array

the code supposes to take values from the array input send them to a function that returns the values into the channel points. the channel is defined globally:

 var points chan float64

and in the main() function:

 points = make(chan float64)

but I keep getting this error:

goroutine 2017 [chan send]:
main.intensity_calc.func1(0xc04206a000, 0xfa1, 0xfa1, 0x3f50624dd2f1a9fc, 0xc0420bb660, 0xc042094000, 0xfa1, 0xfa1, 0xfa1, 0xc0420bb650)
     C:/.../go concurrent calculation.go:71 +0xbf
created by main.intensity_calc
     C:/.../go concurrent calculation.go:76 +0x1c0
  • 写回答

1条回答 默认 最新

  • dongzenglin8292 2017-07-15 09:32
    关注

    The instruction

    var points = make(chan float64)
    

    creates an unbuffered channel, which in turn means that

    points <- contributions_sum(input, distance, input[i][x_ln])
    

    will block until another go-routine reads from points.

    Considering that all the go-routines in the code you posted perform a send on the channel before reading from it, they will all block waiting for a read on the same channel that will never happen (unless this is done in the code you didn't post, which you should have). As a result, you have a deadlock (which is usually written, is the error you quoted everything the console displays?).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分