Sobes.tech
Junior — Middle

How does a Go program behave when GOMAXPROCS = 1 is set and a goroutine with an infinite loop is launched, if you try to execute another part of the code?

sobes.tech AI

Answer from AI

Setting GOMAXPROCS=1 in a Go program limits the number of simultaneously running system threads to one. If you start a goroutine with an infinite loop without calling functions that allow the scheduler to switch contexts (such as time.Sleep, runtime.Gosched), this goroutine will occupy the single thread and block the execution of other goroutines.

As a result, other parts of the code running in different goroutines cannot execute in parallel and will wait until the infinite loop yields control. This is because the Go scheduler switches between goroutines at the user level, but with GOMAXPROCS=1, there is only one OS thread, and if a goroutine does not allow the scheduler to switch, other goroutines are blocked.

Example:

package main

import (
	"fmt"
	"runtime"
	"time"
)

func main() {
	runtime.GOMAXPROCS(1)

	go func() {
		for {
			// infinite loop without yield
		}
	}()

	time.Sleep(time.Second) // give time for the goroutine to start

	fmt.Println("Another part of the code") // may never be executed
}

To avoid blocking, you should insert calls within the infinite loop that allow the scheduler to switch, such as runtime.Gosched() or time.Sleep.

How does a Go program behave when GOMAXPROCS = 1 is… - sobes.tech