https://play.golang.org/p/5A-dnZVy2aAfunc closeChannel(stream chan int) { fmt.Println("closing the channel") close(stream)}func main() { chanOwner := func() <-chan int { resultStream := make(chan int, 5) go func() { defer closeChannel(resultStream) for i := 0; i <= 5; i++ { resultStream <- i } }() return resultStream } resultStream := chanOwner() for result := range resultStream { //this blocks until the channel is closed fmt.Printf("Received: %d\n", result) } fmt.Println("done receiving")}程序輸出closing the channelReceived: 0Received: 1Received: 2Received: 3Received: 4Received: 5done receiving為什么在上述程序中的closing the channel任何語句之前打印語句。Received由于通道的緩沖容量為 5,并且我們正在向其中插入 6 個(gè)元素,因此我希望它在resultStream <- i讀取值并清除緩沖區(qū)中的空間之前阻塞。
1 回答

茅侃侃
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超21個(gè)贊
生成器 goroutine 將通道填充到其容量并阻塞。循環(huán)的接收器從通道接收第一項(xiàng),這再次啟用生成器 goroutine。Received
生成器 goroutine 在接收器 for 循環(huán)打印消息之前運(yùn)行完成,打印closing the channel
消息。然后接收器循環(huán)接收所有剩余的消息。
- 1 回答
- 0 關(guān)注
- 106 瀏覽
添加回答
舉報(bào)
0/150
提交
取消