Reputation: 148
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,
Upvotes: 0
Views: 131
Reputation: 2539
Others have already pointed out in the comments that in terms of being an example, you obviously don't need to write this program with channels.
From your question, though, it sounds like you're curious about why separate goroutines are needed in order for the program to run.
To answer that, it might be helpful to think about how this might work in a world where you were only thinking about threads. You've got your main thread, and that thread invokes sum(s[:len(s)/2], c)
. So now the main thread gets to the c <- sum
line in sum
, and it blocks, because the channel is unbuffered - meaning there must be another listening thread to "take" from that channel in order for our main thread to put something into it. In other words, the threads are passing messages directly to each other, but there's no second thread to pass to. Deadlock!
In this context, goroutines and threads are functionally equivalent. So without a second goroutine, you've got your main goroutine calling...but nobody's picking up the telephone on the other end.
Upvotes: 1