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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.