golang报错: all goroutines are asleep

来源:互联网 发布:github ssh项目源码 编辑:程序博客网 时间:2024/06/16 20:27

在测试go channel时出现如下错误提示:fatal error: all goroutines are asleep - deadlock!

出错信息的意思是在main goroutine线中,期待从其他goroutine线放入数据,但是其他goroutine线都已经执行完了(all goroutines are asleep),那么就永远不会有数据放入管道。
所以,main goroutine线在等一个永远不会来的数据,那整个程序就永远等下去了。 这个时候就会报上述错误。验证:

package mainimport (    "fmt")func main() {    ch1 := make (chan int)    for {        select {        case  <-ch1:            {                fmt.Println("ch1 pop one")            }        }    }}

运行提示错误:

fatal error: all goroutines are asleep - deadlock!

在上面代码中加一个goroutine并sleep,代码会等待该gorutine结束后再打印该错误。

package mainimport (    "fmt"    "time")func main() {    ch1 := make (chan int)    go func() {        fmt.Println("sleep 1")        time.Sleep(5 * time.Second)        fmt.Println("sleep 2")    }()    for {        select {        case  <-ch1:            {                fmt.Println("ch1 pop one")            }        }    }}

打印结果:

sleep 1sleep 2fatal error: all goroutines are asleep - deadlock!
0 0