Golang / GoLang Concurrency Mastery Interview Questions
What is work stealing in Go's scheduler and why does it matter for performance?
Work stealing is the mechanism that keeps all Ps (logical CPUs) busy even when goroutine load is unevenly distributed. It is the key reason Go programs efficiently use all available CPU cores without manual thread pool management.
How it works: each P maintains a local run queue — a lock-free ring buffer of up to 256 runnable Gs. When a P's local queue is empty, instead of blocking, it steals approximately half the Gs from another P's local queue. It also checks the global run queue and the network poller.
// Scheduling check order when a P's local queue is empty: // 1. Every ~61 ticks: check the GLOBAL run queue first // (prevents global queue goroutines from starving) // 2. Local run queue (lock-free) // 3. Work-steal from another random P (takes ~half its Gs) // 4. Global run queue // 5. Network poller (goroutines blocked on net I/O now ready) // Demonstration: 4 CPUs, 1000 goroutines â load distributes automatically var wg sync.WaitGroup for i := 0; i < 1000; i++ { wg.Add(1) go func(id int) { defer wg.Done() // This goroutine may be stolen from one P to another time.Sleep(10 * time.Millisecond) }(i) } wg.Wait() // Visualise stealing with execution tracer: // f, _ := os.Create("trace.out") // trace.Start(f); ...; trace.Stop() // go tool trace trace.out â shows GâP migrations
Why the 61-tick global check? Without it, goroutines that land in the global queue (due to overflow or waking from syscalls) could starve while all Ps have busy local queues. The periodic check ensures fairness.
More Related questions...