0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You're not closing the out channel in the sq function

go func() {
    for number := range in {
        out <- number * number
    }
    close(out)
}()

https://play.golang.org/p/kk8-08SfwB

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.