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
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.
range loops over channels terminate when the channel is closed. Since you never close the channel in your programm, the main goroutine will eventually block forever, trying to receive from c.
Does it make sense to spin up multiple goroutines in a loop for something like calculating a math result?
Depends. If you haven't seen it yet, I can recommend Rob Pike's talk Concurrency is not parallelism. This may give you some intuition about where it is beneficial, and where it isn't.