英文:
How does Go's precise GC work?
问题
Go 1.3实现了一种精确的垃圾收集器。
它是如何精确地识别指针的?
答案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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论