默认情况下在Go中确定了哪些对象,以及它的一些缺陷是什么? [英] Which objects are finalized in Go by default and what are some of the pitfalls of it?
问题描述
函数 runtime.SetFinalizer (x,f interface { })
将与 x
关联的终结器设置为 f
。
默认情况下定义了哪些类型的对象?
默认情况下定义了这些对象会导致一些非预期的陷阱吗?
以下对象默认定价:
ul>
Go标准库不会在除上述对象之外的对象类型上设置终结器。
似乎只有一个可能导致实际程序出现问题的潜在问题:当 os.File
被终结时,它会调用操作系统来关闭文件描述符。通过调用函数 os.NewFile(fd int,name string)* File
创建 os.File
并且文件描述符也被另一个(不同的) os.File
使用,然后垃圾收集或者其中一个文件对象将渲染另一个文件对象不可用。例如:
包主
导入(
fmt
os
runtime
)
func open(){
os.NewFile(1,stdout)
}
func main(){
open()
//强制完成无法访问的对象
_ = make([] byte,1e7)
runtime.GC()
,err:= fmt.Println(some text)//通过os.Stdout打印一些内容
if err!= nil {
fmt .Fprintln(os.Stderr,无法打印文本)
}
}
打印:
无法打印文本
The function runtime.SetFinalizer(x, f interface{})
sets the finalizer associated with x
to f
.
What kind of objects are finalized by default?
What are some of the unintended pitfalls caused by having those objects finalized by default?
The following objects are finalized by default:
os.File: The file is automatically closed when the object is garbage collected.
os.Process: Finalization will release any resources associated with the process. On Unix, this is a no-operation. On Windows, it closes the handle associated with the process.
On Windows, it appears that package
net
can automatically close a network connection.
The Go standard library is not setting a finalizer on object kinds other than the ones mentioned above.
There seems to be only one potential issue that may cause problems in actual programs: When an os.File
is finalized, it will make a call to the OS to close the file descriptor. In case the os.File
has been created by calling function os.NewFile(fd int, name string) *File
and the file descriptor is also used by another (different) os.File
, then garbage collecting either one of the file objects will render the other file object unusable. For example:
package main
import (
"fmt"
"os"
"runtime"
)
func open() {
os.NewFile(1, "stdout")
}
func main() {
open()
// Force finalization of unreachable objects
_ = make([]byte, 1e7)
runtime.GC()
_, err := fmt.Println("some text") // Print something via os.Stdout
if err != nil {
fmt.Fprintln(os.Stderr, "could not print the text")
}
}
prints:
could not print the text
这篇关于默认情况下在Go中确定了哪些对象,以及它的一些缺陷是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!