UDPConn Close真正做了什么?

时间:2014-07-14 02:29:43

标签: networking go udp

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

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

1 个答案:

答案 0 :(得分:4)

好问题,让我们看看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 所以回答你的问题。是。是好的做法,或者你会留在内存网络文件描述符中。

相关问题