【发布时间】:2014-07-14 02:29:43
【问题描述】:
如果 UDP 是无连接协议,那么为什么 UDPConn 有 Close 方法?文档说“关闭关闭连接”,但 UDP 是无连接的。在 UDPConn 对象上调用 Close 是一种好习惯吗?有什么好处吗?
【问题讨论】:
标签: networking go udp
如果 UDP 是无连接协议,那么为什么 UDPConn 有 Close 方法?文档说“关闭关闭连接”,但 UDP 是无连接的。在 UDPConn 对象上调用 Close 是一种好习惯吗?有什么好处吗?
【问题讨论】:
标签: networking go udp
好问题,让我们看看udpconn.Close的代码
http://golang.org/src/pkg/net/net.go?s=3725:3753#L124
func (c *conn) Close() error {
if !c.ok() {
return syscall.EINVAL
}
return c.fd.Close()
}
关闭 c.fd 但 c.fd 是什么?
type conn struct {
fd *netFD
}
ok 是一个netFD 网络文件描述符。我们来看看Close 方法。
func (fd *netFD) Close() error {
fd.pd.Lock() // needed for both fd.incref(true) and pollDesc.Evict
if !fd.fdmu.IncrefAndClose() {
fd.pd.Unlock()
return errClosing
}
// Unblock any I/O. Once it all unblocks and returns,
// so that it cannot be referring to fd.sysfd anymore,
// the final decref will close fd.sysfd. This should happen
// fairly quickly, since all the I/O is non-blocking, and any
// attempts to block in the pollDesc will return errClosing.
doWakeup := fd.pd.Evict()
fd.pd.Unlock()
fd.decref()
if doWakeup {
fd.pd.Wakeup()
}
return nil
}
注意所有decref
所以回答你的问题。是的。是一种很好的做法,否则您将在内存网络文件描述符中徘徊。
【讨论】: