哪个通道端点在双向通道中负责关闭通道?

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

go: which of channels endpoints has to close the channel when its bidirectional?

问题

根据Go语言的哲学,通道应该只由发送方关闭。当通道是双向的时候,应该在哪里关闭它呢?

英文:

Due to Go's philosophy a channel should be closed by the sender only. When a channel is bidirectional where should it be closed?

答案1

得分: 1

问题有点难以解释,因为Go语言没有双向通道。数据只能单向流动 - 从写入者到读取者。

在Go语言中,你可以在通道上拥有多个读取者或写入者。是否有意义取决于上下文。如果你有多个写入者,你需要某种形式的同步来进行关闭操作,例如互斥锁。然而,在每次写操作之前,你还需要锁定它,以确保不会在关闭的通道上写入。如果你在接收方不真正需要知道通道是否关闭,你也可以简单地省略关闭操作,因为垃圾回收器也会正确处理未关闭的通道。

英文:

The question is a little bit hard to interpret since go does not have bidirectional channels. Data flows only in a single direction - from a writer to a reader.

What you can have in Go is multiple readers or writers on a channel. Whether this makes sense depends a little bit on the context. If you have multiple writers you would need some kind of synchronization for the close operation, e.g. a mutex. However you would then also need to lock this before each write operation in order to ensure that you don't write on a closed channel. If you don't really need the information that the channel was closed on receiver side you could also simply omit the close, as the garbage collector will also collect unclosed channels just fine.

huangapple
  • 本文由 发表于 2016年10月25日 22:47:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/40243054.html
匿名

发表评论

匿名网友

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

确定