GOMAXPROCS
- Go course
- Expert
- Lesson 20/34
- 4 min
Learn to set the processor count with GOMAXPROCS.
GOMAXPROCS
GOMAXPROCS is the number of Ps (processors) that can run Go code at once. Its default is the available CPU count. It is set with an environment variable or in code:
GOMAXPROCS=4 ./app
runtime.GOMAXPROCS(4) // returns the old valueChanging it at run time needs a brief stop-the-world; it is usually done once at program start.
When to lower it
When several Go services share CPUs on one machine, or a container's CPU quota is below the core count, setting GOMAXPROCS to the quota reduces CPU throttling and latency spikes. Starting with Go 1.25 the runtime reads the cgroup quota itself and keeps updating if the quota changes.
Practice Worker count
For a CPU-bound worker pool, take the worker count from runtime.GOMAXPROCS(0). Write isciSayisi() int; if the value is below 1 return 1. Print whether the result is 1 or more.
Starter code
package main
import (
"fmt"
"runtime"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"runtime"
)
func isciSayisi() int {
n := runtime.GOMAXPROCS(0)
if n < 1 {
return 1
}
return n
}
func main() {
fmt.Println(isciSayisi() >= 1)
}Expected output
true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In an I/O-heavy service (mostly waiting on the network), what does raising GOMAXPROCS usually give?
- Not much; waiting goroutines don't use a P Correct answer
- Linear speed-up
- Less memory
- A faster network
Explanation: Network waits happen in the netpoller and don't hold a P; if CPU isn't the bottleneck, adding Ps doesn't help.
2 Read without changing
p := runtime.GOMAXPROCS(____)
p := runtime.GOMAXPROCS(0)
Explanation: Passing a value below 1 to GOMAXPROCS doesn't change the setting; it just returns the current value.
3 Situation and advice
| Term | Meaning |
|---|---|
CPU-bound work |
Equal to cores |
I/O-bound work |
Default is enough |
Container with a 2-CPU quota |
2 |
Go 1.25+ |
Reads the quota itself |