Golang / Golang Internals and Memory Management Interview Questions
What does GOMAXPROCS control and how does it affect Go's concurrency model?
GOMAXPROCS sets the number of OS threads (Ps — Processors in the GMP model) that can execute Go code simultaneously. It defaults to the number of logical CPUs available (runtime.NumCPU()). Increasing it allows more goroutines to run in true parallel; the constraint is the number of physical cores, not the number of goroutines.
import "runtime"
// Query current GOMAXPROCS
fmt.Println(runtime.GOMAXPROCS(0)) // 0 = query without changing
fmt.Println(runtime.NumCPU()) // logical CPUs (may include HyperThreading)
// Set programmatically (returns old value)
old := runtime.GOMAXPROCS(4)
// Environment variable
// GOMAXPROCS=2 go run main.go
// Effect on CPU-bound vs I/O-bound workloads:
// CPU-bound: increasing GOMAXPROCS → true parallelism, up to NumCPU
// I/O-bound: even GOMAXPROCS=1 can handle millions of concurrent goroutines
// (blocked goroutines don't hold a P)
// Container / cloud consideration:
// GOMAXPROCS defaults to host CPU count, NOT container CPU quota
// This causes over-scheduling in containers with CPU limits
// Fix: use uber-go/automaxprocs
// import _ "go.uber.org/automaxprocs" // reads cgroup quota automatically
// Benchmark: optimal GOMAXPROCS depends on workload
// CPU-bound matrix multiply: scales linearly to NumCPU
// I/O-bound HTTP server: GOMAXPROCS=2-4 often sufficient; more P's = more
// scheduler overhead without extra throughput on I/O-bound work
// GOMAXPROCS=1 guarantees sequential goroutine execution (useful in tests)
// Some data-race bugs only appear with GOMAXPROCS > 1Container pitfall: by default, Go reads GOMAXPROCS from the host's CPU count, not the container's CPU quota. A Go service running in a 0.5-CPU container may spawn 32 OS threads (matching a 32-core host), causing severe context-switching overhead and latency. The uber-go/automaxprocs library fixes this by reading the cgroup CPU quota and setting GOMAXPROCS accordingly.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
