Sobes.tech
Middle+

What is the GOMAXPROCS variable in Go? Can a program use more threads than specified in GOMAXPROCS?

sobes.tech AI

Answer from AI

Environment variable or parameter GOMAXPROCS in Go sets the maximum number of OS threads that the Go scheduler can use to run goroutines simultaneously.

By default, GOMAXPROCS is equal to the number of logical processors on the machine.

It is important to understand:

  • GOMAXPROCS limits the number of threads that can execute Go code at the same time.
  • However, the program itself can create more threads, for example, for system calls, blocking operations, or through cgo.
  • The Go scheduler (M:N) maps many goroutines onto a limited number of threads specified by GOMAXPROCS.

Thus, the program can have more threads than specified in GOMAXPROCS, but at any given time, no more than GOMAXPROCS threads will be executing Go code.

Example of setting in code:

import "runtime"

func main() {
    runtime.GOMAXPROCS(4) // limit to 4 threads
    // ...
}

This is useful for managing parallelism and optimizing CPU usage.

What is the GOMAXPROCS variable in Go? Can a program… - sobes.tech