go - 范围使用是否需要通道容量?
问题描述
我正在学习golang一段时间。我遇到了频道问题。我有2个例子。它们看起来相同,但其中 1 个给出错误。当我分配通道容量(转换为缓冲通道)时,问题正在解决,但其他示例没有容量分配。
这是我的第一个问题。
第一个代码https://play.golang.org/p/dbC7ZZsagin
// Creating a channel
// Using make() function
mychnl := make(chan string)
// Anonymous goroutine
go func() {
mychnl <- "GFG"
mychnl <- "gfg"
mychnl <- "Geeks"
mychnl <- "GeeksforGeeks"
close(mychnl)
}()
// Using for loop
for res := range mychnl {
fmt.Println(res)
}
第二个代码https://play.golang.org/p/yQMclmwOYs9
// We'll iterate over 2 values in the `queue` channel.
queue := make(chan string, 2)
queue <- "one"
queue <- "two"
close(queue)
// This `range` iterates over each element as it's
// received from `queue`. Because we `close`d the
// channel above, the iteration terminates after
// receiving the 2 elements.
for elem := range queue {
fmt.Println(elem)
}
如果您在第二个代码处删除容量编号,程序将无法运行,我不知道为什么。我想也许对于范围迭代,有必要分配一个容量值,但还有另一个代码可以工作。
从现在开始感谢。
解决方案
对通道进行测距不需要对其进行缓冲。
通信阻塞,直到发送可以继续。如果接收器准备好,则可以在无缓冲通道上进行发送。
你的第二个例子:
queue := make(chan string)
queue <- "one"
queue <- "two"
如果queue
通道没有缓冲,它的第一个发送将阻塞,直到有另一个 goroutine 准备好从它接收。但是你的应用程序中只有一个 goroutine,它只会在发送之后才开始从通道接收:死锁。
当它的缓冲区为 2 时,通道最多可以保存 2 个值。因此,即使没有人准备好接收它,也可以继续发送 2 个值。发送第三个值将再次阻塞。
您的第一个示例也适用于无缓冲通道,因为发送和接收发生在 2 个并发 goroutine 上。
推荐阅读
- c# - 如何使 Combobox(自定义 DataTemplate)中的 SelectedItem 仅显示项目的特定属性
- regex - 如何在 cmd findstr 中使用正则表达式?(正则表达式不起作用)
- html - 找到 FPS 以使用不同的视频 FPS 截取屏幕截图?
- c++ - 我在 C++ 中的函数没有正确传递变量
- php - HTML表单中的php dropzone-将textarea值提交到单独的数据库表
- html - 如何使体育场盒子的高度相互成比例?(HTML 和 CSS)
- angular - 根据路由器 url 有条件地设置样式
- javascript - Three.js:如何将贴图添加到 OBJ 对象以获得逼真的金属材质?
- vba - 通过书签访问填写 Word 文档的数据
- python-3.x - 关于计算强度、产生结果所需时间的预测的问题