關(guān)于chan的疑問
package?main import?( ???"fmt" ) func?main()?{ ???ch?:=?make(chan?string) ???for?i?:=?0;?i?<=?5;?i++?{ ??????go?printHelloWorld(i,?ch) ???} ???for?{ ??????if?msg,ok?:=?<-ch;ok{ ?????????fmt.Println(msg) ??????}else{ ?????????break ??????} ???} } func?printHelloWorld(i?int,?ch?chan?string)?{ ??????ch?<-?fmt.Sprintf("hello?world?%d\n",?i) }
老師:為什么我這段代碼輸出會(huì)有個(gè)??
fatal error: all goroutines are asleep - deadlock!
報(bào)錯(cuò)呢?
2018-06-10
改成這樣就可以了:
2018-06-10
ch沒有關(guān)閉,一直在等待。