The runtime.GOMAXPROCS()
function is used to set the maximum number of CPUs that can be executing simultaneously. It does not directly control the number of Goroutines to run concurrently.
By default, Go uses the number of available CPU cores for concurrency. However, you can use runtime.GOMAXPROCS()
to control the maximum number of concurrent Goroutines specifically.
To set the number of Goroutines to run concurrently, you need to control the number of Goroutines yourself in your code. You can use techniques like synchronization primitives (e.g., channels, mutexes) or a worker pool to limit the maximum number of Goroutines executed concurrently.
Here's an example that demonstrates how to limit the number of Goroutines:
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
maxGoroutines := 5
runtime.GOMAXPROCS(maxGoroutines)
var wg sync.WaitGroup
wg.Add(maxGoroutines)
for i := 0; i < maxGoroutines; i++ {
go func() {
defer wg.Done()
// Perform some work here
fmt.Println("Goroutine executing...")
}()
}
wg.Wait()
}
In the above example, we limit the number of Goroutines to 5 by using runtime.GOMAXPROCS()
. Then, we iterate in a loop and start the Goroutines. Each Goroutine performs some work and prints a message. The sync.WaitGroup
is used to wait for all Goroutines to complete before exiting the program.