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?
The range over the channel blocks because the channel is not closed in sq.
func sq(in <-chan int) <-chan int {
out := make(chan int)
go func() {
for number := range in {
out <- number * number
}
close(out)
}()
return out
}
A good way to debug deadlocks like this is to send the process a SIGQUIT. The runtime dumps the stacks of all the goroutines when a SIGQUIT is received. The stack dumps will often point to the issue.
You're not closing the out
channel in the sq
function
go func() {
for number := range in {
out <- number * number
}
close(out)
}()