golang报错: all goroutines are asleep - deadlock!

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

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

package main

import (
    "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 main

import (
    "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 1
sleep 2
fatal error: all goroutines are asleep - deadlock!

你可能感兴趣的:(golang报错: all goroutines are asleep - deadlock!)