golang GC

golang GC 浅谈

Garbage collector (GC).

The GC runs concurrently with mutator threads, is type accurate (aka precise), allows multiple GC thread to run in parallel. It is a concurrent mark and sweep that uses a write barrier.

golang 的 GC 和工作线程并行运行,?类型准确?,允许多个GC 线程并发运行, 通过 write barrier 实现并发的标记清除。

It is non-generational and non-compacting. Allocation is done using size segregated per P allocation areas to minimize fragmentation while eliminating locks in the common case.

golang GC 不分代,不压缩。 golang 在分配内存的时候是预先将内存划分为固定大小的内存块,以尽量减少碎片,同时消除常见情况下的锁定。

The algorithm decomposes into several steps.
This is a high level description of the algorithm being used. For an overview of GC a good place to start is Richard Jones' gchandbook.org.

gc 算法被分解成多个步骤
这里是对 垃圾回收 算法的高度概括,对于 垃圾回收 算法的综述和入门学习的资料是 Richard Jonesgchandbook.org

The algorithm's intellectual heritage includes Dijkstra's on-the-fly algorithm, see
Edsger W. Dijkstra, Leslie Lamport, A. J. Martin, C. S. Scholten, and E. F. M. Steffens. 1978.
On-the-fly garbage collection: an exercise in cooperation. Commun. ACM 21, 11 (November 1978),
966-975.
For journal quality proofs that these steps are complete, correct, and terminate see
Hudson, R., and Moss, J.E.B. Copying Garbage Collection without stopping the world.
Concurrency and Computation: Practice and Experience 15(3-5), 2003.


1. GC performs sweep termination.

gc 执行清除

a. Stop the world. This causes all Ps to reach a GC safe-point.

SWT(Stop the word):使所有用户线程到达一个 GC 安全点

b. Sweep any unswept spans. There will only be unswept spans if this GC cycle was forced before the expected time.



2. GC performs the "mark 1" sub-phase. In this sub-phase, Ps are
allowed to locally cache parts of the work queue.

     a. Prepare for the mark phase by setting gcphase to \_GCmark
     (from \_GCoff), enabling the write barrier, enabling mutator
     assists, and enqueueing root mark jobs. No objects may be
     scanned until all Ps have enabled the write barrier, which is
     accomplished using STW.

     b. Start the world. From this point, GC work is done by mark
     workers started by the scheduler and by assists performed as
     part of allocation. The write barrier shades both the
     overwritten pointer and the new pointer value for any pointer
     writes (see mbarrier.go for details). Newly allocated objects
     are immediately marked black.

     c. GC performs root marking jobs. This includes scanning all
     stacks, shading all globals, and shading any heap pointers in
     off-heap runtime data structures. Scanning a stack stops a
     goroutine, shades any pointers found on its stack, and then
     resumes the goroutine.

     d. GC drains the work queue of grey objects, scanning each grey
     object to black and shading all pointers found in the object
     (which in turn may add those pointers to the work queue).

write barrier: 写屏障