fatal error all goroutines are asleep deadlock [duplicate]

南楼画角 提交于 2021-01-27 09:33:31

问题


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)
    }
}

回答1:


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)
  }
}

playground example



来源:https://stackoverflow.com/questions/34572122/fatal-error-all-goroutines-are-asleep-deadlock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!