关闭的通道 vs 空通道

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

Closed channel vs nil channel

问题

关闭一个通道和将其设置为nil之间有什么区别?

编辑:

在这个示例中,我想通过关闭通道或将其设置为nil来断开发送者和接收者之间的连接。这样做的最佳实践是什么?

英文:

I am working with Go channels, and I was wondering what's the difference between closing a channel and setting it to nil?

Edit:

In this example, I would like to disconnect the sender and receiver by, whether closing the channel or setting to nil. What's the best practice to do this?

答案1

得分: 29

将一个通道变量设置为nil只是将变量设置为nil,同时保留之前引用的通道的初始化状态。

这与将任何其他变量设置为nil是一样的。

如果还有其他引用指向该通道,你仍然可以访问它。如果没有引用,它将被垃圾回收。

此外,当写入或读取时,nil和关闭的通道的行为是不同的。我建议阅读Dave Cheney的博文Channel Axioms中的内容:

  • 向nil通道发送数据会永远阻塞
  • 从nil通道接收数据会永远阻塞
  • 向关闭的通道发送数据会引发panic
  • 从关闭的通道接收数据会立即返回零值
英文:

Setting a channel variable to nil simply sets the variable to nil, while leaving the channel it had previously referred to initialized.

It's the same as setting any other variable to nil.

If there are other references to the channel, you could still access it. If there are not, it will be garbage collected.

Additionally, nil versus closed channels behave differently when writing or reading. From Dave Cheney's blog post, Channel Axioms, which I recommend reading in its entirety:

> - A send to a nil channel blocks forever
> - A receive from a nil channel blocks forever
> - A send to a closed channel panics
> - A receive from a closed channel returns the zero value immediately

答案2

得分: 8

另一个关键的区别在于 select 语句:

  • 当通道是 closed 状态时,它会立即被选中,并且会得到通道类型的 nil 值。
    这可能导致其他通道在 select 语句中永远不会被选中。
  • 当通道是 nil 状态时,它永远不会被选中。
英文:

Another critical difference is with select:

  • a closed channel, will be selected immediately, and get nil value of the channel type.
    Thus may cause the other channels in the select never get selected.
  • a nil channel, will never be selected.

答案3

得分: 4

这是一个语言规范中的内容。
你可以永远从关闭的通道接收数据,但在关闭的通道上写入数据会导致运行时错误。
对于空通道的任何操作都会永远阻塞。
这种行为通常在同步方案中使用。

英文:

It's in a language specification.
You can receive from closed channel forever, but writing on closed channel cause runtime panic.
Both operation on a nil channel blocks forever.
Such a behaviour commonly used in synchronization schemes.

huangapple
  • 本文由 发表于 2017年4月26日 00:40:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/43616434.html
匿名

发表评论

匿名网友

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

确定