我已将 channel 缓冲区大小设置为零,例如 var intChannelZero = make(chan int)
, 当从 intChannelZero
获取值(value)时将被阻止,直到 intChannelZero
有值(value)。
此外,我将 channel 缓冲区大小设置为 1,例如 var intChannelOne = make(chan int, 1)
, 当从 intChannelOne
获取值(value)时将被阻止,直到 intChannelOne
有值(value)。
我们知道 intChannelZero
的容量为零,intChannelOne
的容量是一个,所以我想知道:
- 为
intChannelZero
赋值时喜欢intChannelZero <- 1
,值(value)保存在哪里? intChannelZero
之间的区别和intChannelOne
为他们赋予值(value)时。
谁能在Golang Runtime Enviroment 层面解释一下?非常感谢。
最佳答案
如果 channel 是无缓冲的(容量为零),则只有当发送方和接收方都准备就绪时,通信才会成功。
如果 channel 被缓冲(容量 >= 1),则如果 channel 未满则发送成功且不会阻塞,如果缓冲区不为空则接收成功且不会阻塞。
When putting a value to the intChannelZero like intChannelZero <- 1, where the value be saved?
值从发送方复制到接收方。除了实现可能使用的任何临时变量外,该值不会保存在任何地方。
The differences between intChannelZero and intChannelOne when putting a value to them.
在 intChannelZero block 上发送,直到接收器准备就绪。
发送 intChannelOne block ,直到缓冲区中有可用空间。
关于go - golang中 channel 缓冲容量为0和1的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53348202/