Principal
Is it possible to control the number of OS threads for goroutines?
sobes.tech AI
Answer from AI
In Go, you can control the number of OS threads (M — OS threads) on which goroutines run using the runtime.GOMAXPROCS(n) function. This function sets the maximum number of OS threads that can execute goroutines simultaneously.
For example:
import (
"runtime"
"fmt"
)
func main() {
runtime.GOMAXPROCS(4) // allow up to 4 OS threads
fmt.Println("Maximum number of OS threads for goroutines:", runtime.GOMAXPROCS(0))
}
By default, GOMAXPROCS is set to the number of logical CPUs on the machine. Changing this value allows controlling parallelism, but not the number of goroutines themselves — there can be thousands, and they are scheduled on available OS threads.
Thus, managing the number of OS threads for executing goroutines is possible, but it is not about controlling the number of goroutines themselves, rather about setting the level of parallelism.