On Mon, Nov 1, 2021 at 9:30 AM Shanshan He <
he8...@gmail.com> wrote:
>
> Hello, I'm reading the GC code recently, but I didn't find any code about analyzing whether an object is reachable or not (or say whether a pointer is live), can someone give me some hints?
>
> I see that each heap word corresponds to a heapBits. By doing & operation with bitscan and bitPointer we can judge whether it has more pointers and whether it is a pointer, but do we need to judge whether a pointer is live? For example, we apply for a piece of memory in a function, do some calculations through a pointer, and then return from the function, assuming that this piece of memory is useless. In the next GC, how to determine that the pointer in this function is dead and we can reclaim this memory?
To answer your last question first, the GC determines that a pointer
is dead by marking all live pointers. Once that is done, any unmarked
pointer is dead.
The process of marking live pointers is done by marking memory
starting from roots, where roots are global variables and live
pointers on goroutine stacks. The code for this is complex, of
course, but all the key steps can be found in the source file
runtime/mgcmark.go.
Hope that helps.
Ian