package main
import (
"fmt"
"time"
)
func main() {
p := producer()
for c := range p {
fmt.Println(c)
}
}
func producer() <-chan string {
ch := make(chan string)
go func() {
for i := 0; i < 5; i++ {
ch <- fmt.Sprint("hello", i)
time.Sleep(1 * time.Second)
}
// commented the below to show the issue
// close(ch)
}()
return ch
}
運行上面的代碼將打印5條消息,然後給出一個「所有去例程是睡眠 - 死鎖錯誤」。我明白,如果我關閉了頻道,錯誤消失了。瞭解走通道死鎖
我想了解的是,運行時如何知道代碼將無限期地等待在通道上,並且沒有其他任何事情將數據發送到通道中。
現在,如果我爲main()函數添加額外的例程,它不會拋出任何錯誤並持續等待通道。
go func() {
for {
time.Sleep(2 * time.Millisecond)
}
}()
那麼,這是否意味着.. Go運行時只是尋找一個運行去例程可能將數據發送到通道中,因此不扔僵局錯誤的存在?
感謝@Eddy R代表的信息。嘗試給+1,但由於我的低點,系統不允許。 – tblogger