I'm having trouble understanding the use of goroutines and channels in the tour of go. Referencing the code below from:
"https://tour.golang.org/concurrency/2"
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
It runs the sum functions using goroutines with the 'go' keyword in front of them, but all they do is send in values to a channel. They shouldn't have to be run with go routines. However, when removing the go keyword to run the functions as normal I get this error:
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.sum(0xc420059f10, 0x3, 0x6, 0xc420088060)
/tmp/compile33.go:10 +0x5a
main.main()
/tmp/compile33.go:17 +0x99
I can't understand why goroutines are needed here. I might be misunderstanding the concept and would appreciate if anyone more familiar with go could shed some light.
Thanks,