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条)

报告相同问题?

悬赏问题

  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机