I have written some code example from GO Concurrency :
func gen(numbers ...int) <-chan int {
out := make(chan int)
go func() {
for _, number := range numbers {
out <- number
}
close(out)
}()
return out
}
func sq(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for number := range in {
out <- number * number
}
}()
return out
}
so I tried to use above code in my main function like this :
func main() {
result := sq(sq(sq(gen(1, 2, 3, 4))))
fmt.Println(<-result)
fmt.Println(<-result)
fmt.Println(<-result)
fmt.Println(<-result)
fmt.Println("-------------------")
for channelValue := range sq(sq(sq(gen(1, 2, 3, 4)))) {
fmt.Println(channelValue)
}
}
I was confused when I run the code I got this message after the loop:
fatal error: all goroutines are asleep - deadlock
Please help me to understand this. From what I understand is calling the fmt.Prinlnt(result)
x 4 times is the same as the for loop on for channelValue := range sq(sq(sq(gen(1, 2, 3, 4))))
. is this correct?
Could please tell me why I got deadlock after the loop?