Worker Sizing From GOMAXPROCS And NumCPU

runtime.GOMAXPROCS(0) reports the parallelism limit without changing it, and the same query sizes a worker pool instead of hard-coding a count.

GoConfig Management

Code

gosnippet
29 lines
package main

import (
	"fmt"
	"runtime"
)

func main() {
	// GOMAXPROCS(0) 只查询不修改:默认与可用 CPU 数一致
	fmt.Println("num cpu:", runtime.NumCPU())
	fmt.Println("gomaxprocs:", runtime.GOMAXPROCS(0))

	// 传入 n 则收紧并行度,并返回修改前的旧值
	old := runtime.GOMAXPROCS(2)
	fmt.Println("set 2, previous was:", old)
	fmt.Println("now:", runtime.GOMAXPROCS(0))

	// worker 池按查询到的并行度起 goroutine,而不是拍脑袋写死数量
	workers := runtime.GOMAXPROCS(0)
	done := make(chan int)
	for id := 0; id < workers; id++ {
		go func(id int) {
			done <- id * id
		}(id)
	}
	for i := 0; i < workers; i++ {
		fmt.Println("worker result:", <-done)
	}
}

Inside the snippet

Worker Sizing From GOMAXPROCS And NumCPU reduces to the function main.

The loop for id := 0; id < workers; id++ is the only repeated construct. A goroutine does the work; a channel carries the result back, so the two contexts never share memory directly.

Using it

The demo output is labeled (num cpu:, gomaxprocs:, set 2, previous was:), so each printed line points back to the operation that produced it.

Key statements

go func(id int) {
	done <- id * id
}(id)
done := make(chan int)

Interactive Tools for This Topic

FAQ

What does Worker Sizing From GOMAXPROCS And NumCPU print when run?
Run it as a complete program — the output lines carry labels such as `num cpu:`, `gomaxprocs:`, `set 2, previous was:`.