【问题标题】:What does UDPConn Close really do?UDPConn Close 的真正作用是什么?
【发布时间】:2014-07-14 02:29:43
【问题描述】:

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

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

【问题讨论】:

    标签: networking go udp


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2013-02-23
      • 2014-04-26
      • 2015-10-14
      • 1970-01-01
      • 2013-02-27
      • 2011-08-19
      • 2019-10-31
      • 2012-10-17
      • 1970-01-01
      相关资源
      最近更新 更多