缓冲通道在达到容量时不会阻塞写入操作。

huangapple go评论85阅读模式
英文:

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(&quot;closing the channel&quot;)
	close(stream)
}

func main() {
	chanOwner := func() &lt;-chan int {
		resultStream := make(chan int, 5)
		go func() {
			defer closeChannel(resultStream)
			for i := 0; i &lt;= 5; i++ {
				resultStream &lt;- i
			}
		}()
		return resultStream
	}
	resultStream := chanOwner()
	for result := range resultStream { //this blocks until the channel is closed
		fmt.Printf(&quot;Received: %d\n&quot;, result)
	}
	fmt.Println(&quot;done receiving&quot;)
}

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 &lt;- 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.

huangapple
  • 本文由 发表于 2021年10月26日 04:43:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/69714543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定