Go 中的垃圾收集工作由谁来完成?

Who does the garbage collection work in go?

据此specification,go背后有一个标记清除垃圾回收机制。但是谁做的?

您的许多问题都在这里得到解答:

  • What kind of Garbage Collection does Go use?

其余:

But who does it?

Go 实现提供的本机代码运行时库。

(我没看过实现,但是很难想象你可以在Go语言中“在线上”为Go实现一个高性能的GC。)

Go code will compile to native binary, right?

正确。 Go 常见问题解答说得很清楚。

So there will not be a virtual machine like Java which it could rely on.

正确。但是,这没有区别。在Java情况下,GC也是由Java运行时提供的本地代码库实现的。

So who does this dirty work for us? A cryptic thread? Or just a goroutine?

从 Go 1.1 开始,GC 是并行的,所以一定有某种多线程在幕后进行。 Goroutines 是 Go 语言的概念,很难想象您会在本机代码 GC 实现中“在线下”使用它们。 (但我可能是错的...)

但是您还需要了解 goroutines 也需要在引擎盖下使用多个线程。常见问题解答说:

"Why doesn't my multi-goroutine program use multiple CPUs?

You must set the GOMAXPROCS shell environment variable or use the similarly-named function of the runtime package to allow the run-time support to utilize more than one OS thread."

看到了吗?本机/OS 线程在幕后参与。