Explain work stealing and parking
Explain work stealing and parking
When a P has little local work, the Go runtime can look for runnable work elsewhere, including other Ps. This work stealing helps balance execution without routing every operation through a central queue. A goroutine blocked on a channel can be parked, letting the thread execute other work. When the channel operation can proceed the goroutine can become runnable again. Parking a G is different from putting an idle M to sleep.
package main
import ( "fmt" "runtime")
func main() { old := runtime.GOMAXPROCS(1) defer runtime.GOMAXPROCS(old) gate := make(chan struct{}) done := make(chan string) go func() { <-gate; done <- "resumed" }() fmt.Println("release") close(gate) fmt.Println(<-done)}The receiving goroutine may park if it reaches the receive early; if the channel is already closed, it need not park. The result is independent of that timing. Never infer actual parking just from this output: use a trace to inspect a particular run.
Expected output:
releaseresumedIllustrate a queue-balancing model
package main
import ( "fmt")
func main() { a := []int{1, 2, 3, 4} b := []int{} if len(b) == 0 && len(a) > 1 { n := len(a) / 2 b = append(b, a[len(a)-n:]...) a = a[:len(a)-n] } fmt.Println(a, b)}This is a sequential teaching model, not Go runtime code. Real stealing deals with concurrent queue operations, victim selection and other sources of runnable work. Do not assume the runtime always steals exactly half in every situation or assign correctness to a particular P.
Expected output:
[1 2] [3 4]Try it locally
Use a shared jobs channel and two workers to sum 1 through 5. Close the jobs channel, join both workers, and print 15; do not require equal job distribution.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Runtime scheduler 03: Explain work stealing and parking
Check the lesson objective before moving on.
Why does the runtime steal work?
Does the gate example prove the receiver parked?