Sobes.tech
Senior

What ways of switching goroutines do you know? How to switch a goroutine manually?

sobes.tech AI

Answer from AI

In Go, switching between goroutines is handled automatically by the runtime scheduler, which allocates CPU time among them. The main ways to switch goroutines are:

  • Blocking operations: when waiting on a channel, mutex, timer, etc., the goroutine blocks, and the scheduler switches to another.
  • Calling runtime.Gosched(): this is an explicit way to yield the processor, causing the current goroutine to pause and allow others to run.

Example of manual switching:

import "runtime"

func worker() {
    for i := 0; i < 10; i++ {
        // some work
        runtime.Gosched() // yield to the scheduler
    }
}

Thus, runtime.Gosched() is a tool for manual goroutine switching, useful for improving responsiveness or preventing a single goroutine from monopolizing the CPU.