如何在不同平台和容器内确定GOMAXPROCS?

I am curious how does Go runtime determine runtime.NumCPU() (count of CPUs) on various platforms with wildly different characteristics like Linux, macOS and Windows?

For example on Linux: I'm curious if it uses sysfs (/sys) to look at paths like /sys/fs/cgroup/cpu/cpu.cfs_quota_us to determine how many CPUs exist, or procfs (/proc/cpuinfo) (this will be the wrong value in a container environment where container may have access to fewer CPUs than the host CPU count exposed in this file).

Similarly on macOS, how is this value determined?

I know some applications like JVM relies on cgroups memory info exposed on /sys to set their internal heap size etc.

Go GOMAXPROCS is a function of the number of CPUs. The number of CPUs is a function of the processor architecture: 386, amd64, arm, arm64, mips64, ppc64, s390, etc, The operating system provides an interface to the hardware: Linux, OpenBSD, Mac OS, etc. On Linux, we have SYS_sched_getaffinity.

See Go source code in src/runtime.

See Linux documentation command man sched_getaffinity.

The number of CPUs is evaluated at running time, and it is OS dependent. If you take a look inside the Go runtime package, you will see many files with postfixes related to OS and architecture names:

When a Go program is built, only the right runtime file that corresponds to the current OS and architecture is included. The number of CPUs will then be evaluated by the function getncpu.