英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论