对于gc的介绍主要位于 ,以下内容是对注释的翻译。

GC 四个阶段

通过源文件注释得知GC共分四个阶段:

GC performs sweep terminationStop the worldsafepointGC performs the mark phase_GCoff_GCmarkwrite barriesmutator assistsStart the worlddistributed termination algorithmmark terminationGC performs mark terminationStop the world_GCmarkterminationGC performs the sweep phase_GCoffStart the world
runtime.GC()

在每轮GC都会有两次STW发生,每个阶段都会发生一次STW相关的操作。

并发清理(Concurrent sweep)

needs seeping
one-by-one

为了避免当存在未清理的span时,应用会向系统申请更多的内存的问题,当一个goroutine需要另外span时(当前goroutine对应的P没有需要的span),它首先通过清理的方式获取相应的内存大小。当一个goroutine需要分配一些小对象 span 时,会先清理相同大小span ,直到至少释放了一个对象;当一个goroutine需要从heap上分配大对象时,它会清理span,直到至少释放一样大小的页到heap上。有一种情况例外:如果一个 goroutine 清理释放了两个不相邻的one-page span到堆上,将会导致重新分配一个新的two-page span,

GC速率(GC Rate)

GOGCGOGC=100memstatsnext_gc

GC 注意事项

GC期间,将阻塞任何的调用,直到GC结束,即STW期间万物静止的状态,所以会阻塞整个程序的运行。

sweep terminationmarkmark terminationsweepruntime.GC()sweepmark terminatio
sweep

对于触发GC 的几个条件请参考:https://blog.haohtml.com/archives/23911

GC 的三种模式

三种模式:

  • (1)gcBackgroundMode,默认模式,标记与清扫过程都是并发执行的;
  • (2)gcForceMode,只在清扫阶段支持并发;
  • (3)gcForceBlockMode,GC全程需要STW。
// gcMode indicates how concurrent a GC cycle should be.
type gcMode int

const (
	gcBackgroundMode gcMode = iota // concurrent GC and sweep
	gcForceMode                    // stop-the-world GC now, concurrent sweep
	gcForceBlockMode               // stop-the-world GC now and STW sweep (forced by user)
)