drcj64241 2016-01-03 00:19
浏览 101
已采纳

致命错误所有goroutine都处于睡眠死锁状态

This question already has an answer here:

Can you explain the following error: fatal error:
true
true
all goroutines are asleep - deadlock!

package main

import (
    "fmt"
)

func printer(ch chan bool) {
    ch <- true
}

func main() {
    var c chan bool = make(chan bool, 2)

    for i := 0; i < 5; i++ {
        go printer(c)
    }

    for i := range c {
        fmt.Println(i)
    }
}
</div>
  • 写回答

1条回答 默认 最新

  • douchi5822 2016-01-03 00:45
    关注

    Because the channel c is not closed, the range loop does not exit. This code will not block:

    func main() {
      var c chan bool = make(chan bool, 2)
    
      for i := 0; i < 5; i++ {
        go printer(c)
      }
    
      for i := 0; i < 5; i++ {
        fmt.Println(<-c)
      }
    }
    

    <kbd>playground example</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?