What does UDPConn Close really do?

huangapple go评论89阅读模式
英文:

What does UDPConn Close really do?

问题

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

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

英文:

If UDP is a connectionless protocol, then why does UDPConn have a Close method? The documentation says "Close closes the connection", but UDP is connectionless. Is it good practice to call Close on a UDPConn object? Is there any benefit?

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

答案1

得分: 4

好的,以下是udpconn.Close方法的代码:

func (c *conn) Close() error {
	if !c.ok() {
		return syscall.EINVAL
	}
	return c.fd.Close()
}

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吗?

所以回答你的问题,是的,这是一个好的做法,否则网络文件描述符会在内存中悬空。

英文:

Good Question, let's see the code of 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()
   }

Closes c.fd but what is c.fd ?

type conn struct {
   	fd *netFD
}

ok is a netFD net File Descriptor. Let's look at the Close method.

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

}

Notice all the decref
So to answer your question. Yes. Is good practice or you will leave hanging around in memory network file descriptors.

huangapple
  • 本文由 发表于 2014年7月14日 10:29:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/24728805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定