Search code examples
dockergocgroups

How is GOMAXPROCS determined on different platforms and inside containers?


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.


Solution

  • 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.