请教一个协程死锁的问题
type goWorker struct {
// task is a job should be done.
task chan func()
}
func main() {
myf:=func(){
fmt.Println("aaa")
}
m:=&goWorker{
task:make(chan func()),
}
go func(){
m.task<-myf
}()
for f:=range m.task{
if f==nil{
return
}
f()
}
aa:
for{
goto aa
}
}
以上代码输出aaa后马上报死锁,这我可以理解的,除非在m.task<-myf后加一句close(m.task)才不会死锁,但是如果改一下代码,把chan读写换一下位置:
type goWorker struct {
// task is a job should be done.
task chan func()
}
func main() {
myf:=func(){
fmt.Println("aaa")
}
m:=&goWorker{
task:make(chan func()),
}
go func(){
for f:=range m.task{
if f==nil{
return
}
f()
}
}()
m.task<-myf
aa:
for{
goto aa
}
}
这样程序就正常了,不会死锁,但是我无法理解,为什么这情的写法不会死锁,我也没有close chan 啊,难道在主协程写chan,新开的协程里读取就不死锁,反过来就不行?请教一下怎么回事?是什么原理。