Junior — Middle
How is the execution switch between different goroutines implemented in the Go language?
sobes.tech AI
Answer from AI
In the Go language, context switching between goroutines is managed by the Go runtime scheduler, which implements the M:N model — a set of goroutines (M) scheduled on a set of system threads (N).
The Go scheduler is cooperative and preemptive:
- A goroutine can explicitly yield control by calling
runtime.Gosched(), allowing other goroutines to run. - The scheduler can preempt a goroutine at certain points (for example, during blocking operations, system calls, or I/O operations).
- The Go runtime automatically switches context between goroutines, saving their state (stack, registers).
Thus, switching between goroutines occurs within the Go runtime, and programmers usually do not manage this directly.
An example of explicit yielding:
goroutine1 := func() {
for i := 0; i < 5; i++ {
fmt.Println("Goroutine 1 -", i)
runtime.Gosched() // yield execution to other goroutines
}
}
func main() {
go goroutine1()
for i := 0; i < 5; i++ {
fmt.Println("Main goroutine -", i)
}
}
Here, runtime.Gosched() allows switching to other goroutines.