Sobes.tech
Senior

How does the scheduler interrupt a goroutine that has entered an infinite loop?

sobes.tech AI

Answer from AI

In Go, the scheduler does not preempt a goroutine that enters an infinite loop if it does not make system calls or invoke functions that allow the scheduler to switch context (for example, time.Sleep, runtime.Gosched, channel operations). A goroutine can be considered "stuck" if it does not yield control and the scheduler cannot forcibly interrupt it.

Therefore, if a goroutine is in an infinite loop without calls, the scheduler will not be able to switch to other goroutines, leading to a deadlock. To prevent this, you should explicitly call runtime.Gosched() or use other mechanisms that allow the scheduler to switch execution.

Example:

for {
    // ... work
    runtime.Gosched() // yield to the scheduler
}
How does the scheduler interrupt a goroutine that has… - sobes.tech