Middle
How can you control the number of threads used for goroutine execution?
sobes.tech AI
Answer from AI
In Go, the number of OS threads used to execute goroutines is managed using the runtime.GOMAXPROCS(n) function. This function sets the maximum number of operating system threads that can simultaneously execute user-level Go code.
By default, GOMAXPROCS is set to the number of logical CPUs on the machine. Changing this value allows you to control the program's parallelism.
Example:
package main
import (
"fmt"
"runtime"
)
func main() {
fmt.Println("Default GOMAXPROCS:", runtime.GOMAXPROCS(0)) // Get current value
runtime.GOMAXPROCS(2) // Set maximum to 2 threads
fmt.Println("Updated GOMAXPROCS:", runtime.GOMAXPROCS(0))
}
It is important to understand that GOMAXPROCS affects the parallel execution of goroutines but does not limit their number — there can be thousands of goroutines, and they are scheduled on available threads.