英文:
buffered channel not blocking for write when reached its capacity
问题
为什么在上面的程序中,closing the channel
语句在任何Received
语句之前打印出来?由于通道的缓冲区容量为5,并且我们正在向其中插入6个元素,我原以为它会在resultStream <- i
之前阻塞,直到读取并清除缓冲区中的一个值。
英文:
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")
}
Output of program
closing the channel
Received: 0
Received: 1
Received: 2
Received: 3
Received: 4
Received: 5
done receiving
why is the closing the channel
statement printed before any Received
in the above program. since the channel is buffered with a capacity of 5, and we are inserting 6 elements into it, I was expecting it to block at the resultStream <- i
before a value was read and cleared up space in the buffer.
答案1
得分: 4
生成器goroutine将通道填满到其容量,并阻塞。接收器循环从通道接收第一个项目,这使得生成器goroutine再次运行。生成器goroutine在接收器循环打印“Received”消息之前完成运行,打印“关闭通道”消息。然后接收器循环接收所有剩余的消息。
英文:
The generator goroutine fills the channel to its capacity and blocks. The receiver for loops receives the first item from the channel, which enables the generator goroutine again. The generator goroutine runs to completion before the receiver for-loop can print the Received
message, printing the closing the channel
message. Then the receiver loop receives all remaining messages.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论