英文:
Close() invocations and the garbage collector
问题
在Go语言中,使用像网络连接这样的资源的接口通常会有一个Close()
方法来释放这些资源。
现在我想知道,如果实现接口的相关结构体在没有调用Close
的情况下被垃圾回收,会发生什么。
操作系统会保持网络连接/文件描述符/其他资源打开吗?垃圾回收器会做些什么,还是有其他东西会阻止它触及该结构体?
也就是说,
conn, _ := net.DialTCP(network, laddr, raddr)
// 做一些操作,然后
conn = nil
// 忘记调用`Close()`了!
// 现在会发生什么?
英文:
In Go, interfaces that use resources like network connections usually have a Close()
method that disposes of these resources.
Now I wonder what would happen if the associated structs implementing the interface get garbage-collected without Close
having been invoked.
Will the OS keep the network connection / file descriptor / whatever open? Will the garbage collector do something or will something even prevent it from touching that struct?
I.e.
conn, _ := net.DialTCP(network, laddr, raddr)
// do stuff, then
conn = nil
// forgot to invoke `Close()`!!
// what happens now?
答案1
得分: 5
这样的可关闭资源可以使用runtime.SetFinalizer
设置最终器,例如TCPListener
的netFD
:
runtime.SetFinalizer(fd, (*netFD).Close)
这并不意味着可以省略调用Close()
来释放资源,因为不能保证最终器会被调用或者何时被调用:
> 最终器在程序无法再访问到obj指向的对象之后的某个任意时间被调度运行。不能保证最终器会在程序退出之前运行,因此它们通常只用于在长时间运行的程序中释放与对象相关的非内存资源。
调用Close()
以确保资源被释放。
相关链接:
英文:
Such closeable resources may have finalizers set with runtime.SetFinalizer
, for example the netFD
of TCPListener
:
runtime.SetFinalizer(fd, (*netFD).Close)
This should not be a reason for omitting to call Close()
to free resources, also because there is no guarantee that the finalizer will be called or when:
> The finalizer is scheduled to run at some arbitrary time after the program can no longer reach the object to which obj points. There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program.
Call Close()
to make sure the resources are freed.
Related:
答案2
得分: 2
操作系统将保留未关闭连接的文件描述符,这些文件描述符将在程序退出时释放。
英文:
Os will keep the file descriptors for non-closed connections, which is going to be freed once the program exits.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论