https://play.golang.org/p/5A-dnZVy2aA
func 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 channel
Received: 0
Received: 1
Received: 2
Received: 3
Received: 4
Received: 5
done receiving
為什么該closing the channel陳述句列印在Received上述程式中的any 之前。由于通道的緩沖容量為 5,并且我們正在向其中插入 6 個元素,因此我希望它在resultStream <- i讀取值之前阻塞并清除緩沖區中的空間。
uj5u.com熱心網友回復:
生成器 goroutine 將通道填充到其容量并阻塞。回圈接收器從通道接收第一項,這再次啟用生成器 goroutine。在接收者 for 回圈可以列印Received訊息之前,生成器 goroutine 運行到完成,列印closing the channel訊息。然后接收器回圈接收所有剩余的訊息。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/338485.html
