doudaiyao0934 2011-12-21 19:49
浏览 23
已采纳

默认情况下,哪些对象在Go中完成了,它有哪些陷阱?

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?

  • 写回答

3条回答 默认 最新

  • doubang9906 2011-12-21 19:54
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题