2014-07-14 52 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 因此,要回答你的問題。是。是好的做法,否則你會留在內存網絡文件描述符中。