golang死锁问题(fatal error: all goroutines are asleep - deadlock!)

新手上路,请多包涵
package main

import (
    "fmt"
    _"time"
)

var (
    foo6Chan = make(chan int, 10)
)

func foo6() {
    for val := range foo6Chan {
        go func() {
            fmt.Printf("foo6 val = %d\n", val)
        }()
    }
}

func main() {
    foo6Chan <- 1
    foo6Chan <- 2
    foo6Chan <- 3
    foo6Chan <- 5
    foo6()
    //time.Sleep(2 * time.Second)
}

执行报错

foo6 val = 5
foo6 val = 5
foo6 val = 5
foo6 val = 5
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.foo6()
    /Users/plsof/4.go:13 +0x94
main.main()
    /Users/plsof/4.go:25 +0x96
exit status 2

如果我把foo6() 改为 go foo6() 执行ok

package main

import (
    "fmt"
    "time"
)

var (
    foo6Chan = make(chan int, 10)
)

func foo6() {
    for val := range foo6Chan {
        go func() {
            fmt.Printf("foo6 val = %d\n", val)
        }()
    }
}

func main() {
    foo6Chan <- 1
    foo6Chan <- 2
    foo6Chan <- 3
    foo6Chan <- 5
    go foo6()
    time.Sleep(2 * time.Second)
}

想请教一下这个是怎么回事了

阅读 5k
1 个回答

报错是因为没有关闭foo6Chan这个channel,会一直阻塞在for循环。

解决:

...
foo6Chan <- 5
close(foo6Chan) // 关闭channle
foo6()

添加go关键字不报错是因为在另一个线程中阻塞了,2秒后主函数结束会杀掉线程。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏