219

如果我从不检查其状态,是否可以让 Go 通道永远打开(永远不要关闭通道)?会不会导致内存泄露?下面的代码可以吗?

func (requestCh chan<- Request) GetResponse(data RequestData) Response {
    reply := make(chan Response)
    requestCh <- Request{data: data, replyCh: reply}
    return <-reply
}
4

6 回答 6

332

让 Go 通道永远打开并且永远不要关闭它是可以的。当通道不再使用时,它将被垃圾回收。

请注意,仅当接收器正在寻找关闭时才需要关闭通道。关闭通道是通道上的控制信号,指示没有更多数据跟随。

设计问题:通道关闭

于 2011-12-21T17:40:30.353 回答
46

是的,保持通道打开是可以的。正如Go 编程语言书所述:

完成后无需关闭每个频道。只有当告诉接收 goroutine 所有数据都已发送很重要时,才需要关闭通道。垃圾收集器确定无法访问的通道将回收其资源,无论它是否关闭。(不要将此与打开文件的关闭操作混淆。 完成后对每个文件调用Close方法很重要。)

于 2016-04-14T04:31:54.490 回答
9

是的,让通道保持打开状态是可以的,实际上这是典型的。打开的通道并不构成对通道对象的引用,因此不会阻止它被垃圾收集。

于 2011-12-21T17:46:59.043 回答
8

"One general principle of using Go channels is don't close a channel from the receiver side and don't close a channel if the channel has multiple concurrent senders."

As clearly mentioned in answer above that every channel will be GCed eventually once it is marked for cleanup, so it is okay to leave channel un-closed the only difference it will make is that that channel will be available for gc after a few cycles maybe if not closed explicitly.

Also the following articles this and this shows various ways to close a channel in case of 1:N, N:1 or M:N (senders:receivers)

于 2020-04-13T18:27:57.673 回答
2

上面已经很好地介绍了这一点,但是我发现A Tour of Go中的以下内容非常清楚,这也给出了 when to 的示例close

另一个注意事项:频道不像文件;您通常不需要关闭它们。仅当必须告诉接收器没有更多值到来时才需要关闭,例如终止range循环。

于 2021-07-02T22:44:16.033 回答
-2

Go 是垃圾收集器,因此您实际上不必“释放”任何东西。

有可能关闭通道,但它主要用作 - close(channel) - 告诉 goroutine(或主程序)不会在该通道上发送任何其他内容。

于 2011-12-21T17:19:53.550 回答