dreamy1992 2017-09-26 15:57
浏览 12
已采纳

从概念上讲,这是使用goroutines的正确方法(我的代码有什么问题)

I have two question:

a) Does it make sense to spin up multiple goroutines in a loop for something like calculating a math result?

b) Why doesn't my code work (this is my first attempt at goroutines)? I'm guessing it has something to do with closing the channel.

package main

import (
    "fmt"
    "math"
    "sync"
)

func main() {
    input := [][]int{
        []int{10, 9},
        []int{5, 2},
        []int{4, 9},
    }

    var wg sync.WaitGroup
    c := make(chan int)
    for _, val := range input {
        wg.Add(1)
        go func(coordinates []int, c chan int) {
            defer wg.Done()
            c <- calculateDistance(coordinates[0], coordinates[1])
        }(val, c)
    }
    distances := []int{}

    for val := range c {
        distances = append(distances, val)
    }
    wg.Wait()
    fmt.Println(distances)
}

func calculateDistance(x int, y int) int {
    v := math.Exp2(float64(x)) + math.Exp2(float64(y))
    distance := math.Sqrt(v)
    return int(distance)
}

Playground link: https://play.golang.org/p/0iJ9hFnb8R

  • 写回答

2条回答 默认 最新

  • doumeitang572461 2017-09-26 16:09
    关注

    a) Yes it can make sense to spin up multiple go routines to do CPU bound tasks, if you have multiple CPU's. Also it's super important to profile your code to see if there is actually any benefit. You could use go's built in benchmark framework to help do this.

    Because you're limited by CPU it could be a good start to do synchronously, then to bound your goroutines to the number of CPU cores instead of the # of items in your input list, but really it should be metrics driven to see. Go provides amazing toolchain using benchmarks and pprof to empirically determine what is the most efficient approach :)

    b) https://play.golang.org/p/zGEQGC9EIy Your channel never closes and your main thread never end. The example waits until all go routines finish their work, then closes the channel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容