doumi9618
doumi9618
2017-02-09 22:58
浏览 148
已采纳

for循环导致死锁

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条回答 默认 最新

  • douchuoliu4422
    douchuoliu4422 2017-02-09 23:16
    已采纳

    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.

    点赞 评论
  • doukang7858
    doukang7858 2017-02-09 23:16

    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

    点赞 评论

相关推荐