2014-07-14 32 views

回答

3

好问题,让我们看到的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 因此,要回答你的问题。是。是好的做法,否则你会留在内存网络文件描述符中。