gpt4 book ai didi

garbage-collection - 默认情况下,Go 中哪些对象是最终确定的,它有哪些陷阱?

转载 作者:IT王子 更新时间:2023-10-29 01:19:14 25 4
gpt4 key购买 nike

函数<a href="http://golang.org/pkg/runtime/#SetFinalizer" rel="noreferrer noopener nofollow">runtime.SetFinalizer</a>(x, f interface{})设置与 x 关联的终结器至 f .

什么样的对象是默认完成的?

默认终结这些对象会导致哪些意外陷阱?

最佳答案

默认完成以下对象:

  • os.File : 当对象被垃圾回收时,文件自动关闭。

  • os.Process :完成将释放与进程关联的任何资源。在 Unix 上,这是一个空操作。在 Windows 上,它关闭与进程关联的句柄。

  • 在 Windows 上,显示包 net可以自动关闭网络连接。

Go 标准库没有为上述以外的对象类型设置终结器。

似乎只有一个潜在的问题可能会导致实际程序出现问题:当一个os.File 完成时,它会调用操作系统关闭文件描述符。如果 os.File 是通过调用函数 os.NewFile(fd int, name string) *File 创建的,并且文件描述符也被另一个(不同的)使用os.File,然后对其中一个文件对象进行垃圾回收任一个将使另一个文件对象不可用。例如:

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")
}
}

打印:

could not print the text

关于garbage-collection - 默认情况下,Go 中哪些对象是最终确定的,它有哪些陷阱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8595457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com