liveBook · Manning

GOMAXPROCS

As explained in 100 Go Mistakes and How to Avoid Them

runtime.GOMAXPROCS is a Go runtime function that sets or reports the maximum number of logical CPUs available for simultaneous Go execution.

A common mistake is to treat GOMAXPROCS as either a cap on goroutines or a guarantee about how many OS threads exist. It limits the threads executing Go code simultaneously; the runtime can create additional threads when others block in system calls. Since Go 1.5, its default has been based on available logical CPUs. section 8.2.1

Size a CPU-bound worker pool

Use `n := runtime.GOMAXPROCS(0)` to read the current value without changing it. A fixed pool doing CPU-bound work can use a worker count close to `n`. For I/O-bound work, choose a count based mainly on how many concurrent requests the external system can handle—not on GOMAXPROCS alone. section 8.5 section 8.7

A worker count does not guarantee that every worker runs immediately. Goroutines may remain runnable in scheduler queues until threads pick them up; work stealing can distribute them later. section 8.2.1 section 8.5

spec:
  containers:
  - name: myapp
    image: myapp
    resources:
      limits:
        cpu: 4000m

The Kubernetes configuration limits a container to four CPU cores, but on the eight-core host in this example GOMAXPROCS defaults to 8. Do not assume the container limit sets it to 4: a mismatch can contribute to CPU throttling under the CFS quota. section 12.10

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains the scheduler limit, reading it without changes, worker-pool implications, and its interaction with Kubernetes CPU quotas.
Examples
Uses a four-core worker-pool scenario and a Kubernetes container limited to four cores on an eight-core host.
What it assumes
Assumes familiarity with goroutines and worker pools while defining scheduler roles and showing how to read the current setting.
What you can do after
Operate/configure it by reading the current value with runtime.GOMAXPROCS(0) and using it to guide CPU-bound pool sizing.
How it connects
Connects goroutine scheduling and work stealing to worker pools, I/O-bound workloads, Kubernetes CPU limits, and CFS throttling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.