如果 GOMAXPROCS 太大怎么办?

What if GOMAXPROCS is too large?

我们都知道runtime.GOMAXPROCS默认设置为CPU核心数,如果这个属性设置太大了怎么办?

  1. 程序会有更多上下文切换吗?
  2. 垃圾收集器会更频繁地被触发吗?

GOMAXPROCS 默认设置为可用逻辑 CPU 的数量是有原因的:这在大多数情况下提供最佳性能。

GOMAXPROCS 仅限制 "active" 线程的数量,如果线程的 goroutine 被阻塞(例如被系统调用),则可能会启动一个新线程。没有直接关联,参见

如果GOMAXPROCS大于可用数量CPU,则活动线程数将多于CPU个内核,这意味着活动线程必须"multiplexed"到可用的处理单元,所以是的,会有更多的上下文切换如果活动线程多于内核,情况不一定如此。

垃圾收集与线程数没有直接关系,因此您不必担心。引用包 runtime:

The GOGC variable sets the initial garbage collection target percentage. A collection is triggered when the ratio of freshly allocated data to live data remaining after the previous collection reaches this percentage. The default is GOGC=100. Setting GOGC=off disables the garbage collector entirely. The runtime/debug package's SetGCPercent function allows changing this percentage at run time. See https://golang.org/pkg/runtime/debug/#SetGCPercent.

如果您有更多线程不分配/释放内存,那应该不会影响触发集合的频率。

在某些情况下,将 GOMAXPROCS 设置为高于 CPU 的数量会提高应用的性能,但这种情况很少见。衡量一下,看看它是否对您的情况有帮助。