缓冲通道似乎存储的值比我的缓冲区大小要多。

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

Buffered channel appears to store more values than my buffer size

问题

我目前正在学习有关通道的知识,并编写了这段代码,期望它会失败,但实际上它没有。在这里底层到底发生了什么?根据我的理解,如果缓冲区大小为2,那么我应该只能同时存储2个值,否则会发生死锁。我是否从一开始就缺乏了基本的理解?

所以在思考之后,也许通道被填满了2个值,并在内存解锁后并发地执行每个Println(<-c)。我编写了下面的代码片段,试图阻止这种情况发生并引发死锁错误,但它也成功运行了。

为什么这个带缓冲的通道似乎允许我在其中存储超过2个值?如果我对通道的基本理解是错误的,有人能给我一个好的资源来纠正吗?

英文:

I'm currently learning about channels and have written this code expecting it to fail but it didn't. What is actually happening under the hood here? From my understanding if the buffer size is 2, then I should only be able to store 2 values at a time without getting deadlocked. Am I missing a fundamental understanding off the bat?

c := make(chan int, 2)

go func() {
	c &lt;- 1
	c &lt;- 2
	c &lt;- 3
	c &lt;- 4
	c &lt;- 5
	c &lt;- 6
}()

fmt.Println(&lt;-c)
...
fmt.Println(&lt;-c)

So after thinking maybe the channel is getting filled with 2 values and concurrently executing each Println(<-c) once the memory is unlocked for whatever reason. I wrote the next snippet trying to stop that from happening and cause the deadlock error and it ran as well.

c := make(chan int, 2)

go func() {
	c &lt;- 1
	c &lt;- 2
	c &lt;- 3
	c &lt;- 4
	c &lt;- 5
	c &lt;- 6
}()

fmt.Println(&lt;-c, &lt;-c, &lt;-c, &lt;-c, &lt;-c, &lt;-c)

Why does this buffered channel appear to allow me to store more than 2 values in it, and if my fundamental understanding of channels is incorrect, could someone lead my to a good source to correct it?

答案1

得分: 1

它只存储两个值。goroutine开始运行,并逐个向通道写入。但同时,主goroutine也在运行,并从通道中读取。你读取足够的值来消耗通道中的所有值,所以没有死锁。

英文:

It is storing only two values. The goroutine starts running, and writes to the channel one by one. But at the same time, the main goroutine is also running, and reading from the channel. You read just enough to consume all the values in the channel, so no deadlock.

huangapple
  • 本文由 发表于 2022年9月2日 08:47:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73576726.html
匿名

发表评论

匿名网友

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

确定