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)
}
想请教一下这个是怎么回事了
报错是因为没有关闭
foo6Chan
这个channel,会一直阻塞在for
循环。解决:
添加
go
关键字不报错是因为在另一个线程中阻塞了,2秒后主函数结束会杀掉线程。