Junior — Middle
What consequences will occur in the program's operation when GOMAXPROCS is set to 1 and an infinite goroutine is launched?
sobes.tech AI
Answer from AI
Setting GOMAXPROCS to 1 limits the number of OS threads that the Go scheduler can use to one thread. If you then launch an infinite goroutine, the following happens:
- All computations will be executed sequentially in one thread.
- If the infinite goroutine does not contain points where context switching occurs (e.g., blocking calls or
runtime.Gosched()), other goroutines may not get execution time, leading to a "hang". - As a result, the program may become unresponsive or work very slowly because the scheduler cannot effectively switch between goroutines.
Example:
package main
import (
"runtime"
"time"
"fmt"
)
func main() {
runtime.GOMAXPROCS(1)
go func() {
for {
// infinite loop without calling runtime.Gosched()
}
}()
time.Sleep(time.Second)
fmt.Println("Program finished")
}
In this example, the main goroutine may not get execution time if the infinite goroutine does not yield control, which can lead to a hang.