Junior — Middle
Is the number of goroutines created related to the number of CPU cores?
sobes.tech AI
Answer from AI
The number of goroutines created in Go is not directly related to the number of CPU cores. You can create many goroutines — they are lightweight threads managed by the Go runtime, and their number is mainly limited by available memory and program logic.
The number of cores affects the number of OS threads that can run simultaneously, and the GOMAXPROCS parameter sets the maximum number of threads executing goroutines in parallel. However, the number of goroutines usually far exceeds the number of cores, as they are efficiently scheduled and switched within the runtime.
Example:
runtime.GOMAXPROCS(4) // Use 4 cores
for i := 0; i < 1000; i++ {
go func(n int) {
fmt.Println("Goroutine", n)
}(i)
}
time.Sleep(time.Second)
Here, 1000 goroutines are created, although there are only 4 cores.