gpt4 book ai didi

networking - UDPConn Close 到底做了什么?

转载 作者:IT王子 更新时间:2023-10-29 00:44:14 26 4
gpt4 key购买 nike

如果 UDP 是无连接协议(protocol),那么为什么 UDPConn 有一个 Close 方法?文档说“关闭关闭连接”,但 UDP 是无连接的。在 UDPConn 对象上调用 Close 是一种好习惯吗?有什么好处吗?

http://golang.org/pkg/net/#UDPConn.Close

最佳答案

好问题,看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所以来回答你的问题。是的。这是一种很好的做法,否则您将留在内存网络文件描述符中。

关于networking - UDPConn Close 到底做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24728805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com