Senior
When does cooperative (non-preemptive) goroutine switching occur?
sobes.tech AI
Answer from AI
In Go, cooperative goroutine switching (non-preemptive switching) occurs in the following cases:
- When a goroutine performs operations that explicitly invoke the scheduler, such as calling
runtime.Gosched(). This allows the current goroutine to yield control to other goroutines. - During blocking operations, such as waiting on a channel, input/output, or synchronization, the goroutine is suspended, and the scheduler switches to another.
Thus, cooperative switching happens when a goroutine voluntarily yields control, unlike preemptive switching, where the scheduler forcibly switches context.
Example:
func main() {
go func() {
for i := 0; i < 5; i++ {
fmt.Println("Goroutine 1", i)
runtime.Gosched() // yield control
}
}()
for i := 0; i < 5; i++ {
fmt.Println("Main goroutine", i)
runtime.Gosched()
}
}