Go语言的精确垃圾回收(GC)是如何工作的?

huangapple go评论74阅读模式
英文:

How does Go's precise GC work?

问题

Go 1.3实现了一种精确的垃圾收集器。

它是如何精确地识别指针的?

英文:

Go 1.3 implements a precise garbage collector.

How does it precisely identify pointers?

答案1

得分: 5

阅读《垃圾收集器的更改》,机制似乎很简单:

从Go 1.3开始,运行时假设指针类型的值包含指针,而其他值则不包含。

这个假设对于栈扩展和垃圾收集的精确行为都是基本的。

使用unsafe包将整数存储在指针类型的值中的程序是非法的,如果运行时检测到这种行为,程序将崩溃。使用unsafe包将指针存储在整数类型的值中的程序也是非法的,但在执行过程中更难诊断。

这个reddit帖子补充说:

基本上,垃圾收集器必须找出哪些对象是可达的,为此它必须遵循堆栈上的指针,指向它们指向的每个对象的指针,然后遵循对象中的指针,直到不再遇到新的对象。垃圾收集器未遇到的每个对象都是垃圾。

问题在于,这需要垃圾收集器知道指针是什么:

  • 精确的垃圾收集器具有这些信息,
  • 保守的垃圾收集器必须假设如果堆栈上的值与分配对象的地址相同,则它可能是指针。

结果是,保守的垃圾收集器倾向于保留许多不可达的对象,并且需要做更多的工作(遍历死对象图)。

英文:

Looking at "Changes to the garbage collector", the mechanasim seems simple:

> Starting with Go 1.3, the runtime assumes that values with pointer type contain pointers and other values do not.

> This assumption is fundamental to the precise behavior of both stack expansion and garbage collection.

> Programs that use package unsafe to store integers in pointer-typed values are illegal and will crash if the runtime detects the behavior.
Programs that use package unsafe to store pointers in integer-typed values are also illegal but more difficult to diagnose during execution.

This reddit thread add:

> Basically a GC has to find out which objects are reachable, to do this it has to follow pointers lying on the stack to every object they point to and then follow the pointers in the objects to every object they point to until it no longer encounters new objects.
Every object not encountered by the GC is then garbage.

> The problem with that is that it requires the GC to know what a pointer is:

> - a precise GC has that information,

  • a conservative GC has to assume that every value on the stack may be a pointer if it is identical with the address of an allocated object.

> As a result conservate GCs tend to keep a lot of unreachable objects around and have to do more work (traverse dead object graphs).

huangapple
  • 本文由 发表于 2014年10月17日 18:19:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/26422896.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定