在 Go 中哪些对象是默认完成的,它有哪些陷阱? [英] Which objects are finalized in Go by default and what are some of the pitfalls of it?

查看:25
本文介绍了在 Go 中哪些对象是默认完成的,它有哪些陷阱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数runtime.SetFinalizer(x, f interface{}) 将与 x 关联的终结器设置为 f.

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?

推荐答案

默认完成以下对象:

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

  • os.File: The file is automatically closed when the object is garbage collected.

os.Process:最终确定将释放与进程相关的任何资源.在 Unix 上,这是一个无操作.在 Windows 上,它关闭与进程关联的句柄.

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.

在 Windows 上,包 net可以自动关闭网络连接.

On Windows, it appears that package net can automatically close a network connection.

Go 标准库没有为上述对象类型设置终结器.

The Go standard library is not setting a finalizer on object kinds other than the ones mentioned above.

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

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

打印:

could not print the text

这篇关于在 Go 中哪些对象是默认完成的,它有哪些陷阱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆