cfanbo / cfanbo.github.io

1 stars 0 forks source link

Golang什么时候会触发GC | 学习笔记 #250

Open cfanbo opened 7 months ago

cfanbo commented 7 months ago

https://blog.haohtml.com/archives/23911/

Golang采用了三色标记法来进行垃圾回收,那么在什么场景下会触发这个GC动作呢? 源码主要位于文件 src/runtime/mgc.go go version 1.16 触发条件从大方面来说,分为 手动触发 和 系统触发 两种方式。手动触发一般很少用,主要通过开发者调用 runtime.GC() 函数来实现,而对于系统自动触发是 运行时 根据一些条件自行维护的,这也正是本文要介绍的内容。 不管哪种触发方式,底层回收机制是一样的,所以我们先看一下手动触发,看看能否根据它来找GC触发所需的条件。 // src/runtime/mgc.go // GC runs a garbage collection and blocks the caller until the // garbage collection is complete. It may also block the entire // program. func GC() { n := atomic.Load(&work.cycles) // 等待上一轮的标记终止 gcWaitOnMark(n) // We're now in sweep N or later. Trigger GC cycle N+1, which // will first finish sweep N if necessary and then enter sweep // termination N+1.