What objects are terminated in Go by default and what are some of these errors?

The runtime.SetFinalizer (x, f interface{}) function sets the finalizer associated with x to f .

What objects are completed by default?

What are some of the unintended errors caused by these objects being finalized by default?

+4
source share
3 answers

By default, the following objects are completed:

  • os. File : the file closes automatically when the object collects garbage.

  • os. Process : Termination returns any resources associated with the process. On Unix, this is not an operation. On Windows, it closes the handle associated with the process.

  • On Windows, it seems that the net packet might automatically close the network connection.

The Go standard library does not set a finalizer for objects other than those mentioned above.

It seems that there is only one potential problem that can cause problems in real programs. When os.File completes, it will make an OS call to close the file descriptor. If os.File was created by calling the os.NewFile(fd int, name string) *File function, and the file descriptor is also used by another (other) os.File , then garbage collection, or one of the file objects, will make the other The file object is unusable. For instance:

 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 
+7
source

Just go to the os.NewFile source code:

 // NewFile returns a new File with the given file descriptor and name. func NewFile(fd uintptr, name string) *File { fdi := int(fd) if fdi < 0 { return nil } f := &File{&file{fd: fdi, name: name}} runtime.SetFinalizer(f.file, (*file).close) // <<<<<<<<<<<<<< return f } 
  • When you start the GC, it will launch the Finalizer binding on this object.
  • When you open a new file, the go library will bind Finalizer to this returned object for you.
  • When you don't know what the GC will do with this object, go to the source code and check if the library has installed some finalizers on this object.
0
source

"What objects are completed by default?"
Nothing in Go matches IMO by default.

"What are some of the unintended errors caused by these objects being finalized by default?"
As stated above: none.

-4
source

Source: https://habr.com/ru/post/1387453/


All Articles