Exercise 9: D&D Work Stealing - Rolling for Goroutines
Want to learn more? Read The Go Runtime Scheduler on Internals for Interns for a deep dive into how Go’s work stealing scheduler works.
In this exercise, you’ll add a d20 dice roll to Go’s work stealing scheduler. When a processor (P) tries to steal goroutines from another P’s run queue, it must first roll higher than 10 on a twenty-sided die. Failed rolls block the steal, making the scheduler’s load balancing visible and entertaining.
Learning Objectives
By the end of this exercise, you will:
- Understand how Go’s work stealing scheduler distributes goroutines across processors
- Know where the
stealWorkfunction lives and how it iterates over other Ps - Modify the steal logic to add a randomized gate
- Observe work stealing attempts in real time
Introduction: Why Work Stealing?
Go’s scheduler uses work stealing to keep all processors (Ps) busy. Each P has its own local run queue of goroutines. When a P runs out of local work, instead of sitting idle it becomes a thief:
- It checks the global run queue for goroutines
- It checks the network poller for ready goroutines
- It tries to steal goroutines from other Ps’ local queues
Stealing grabs roughly half the victim’s goroutines at once, balancing load without a centralized queue. This avoids the contention of a single global queue while keeping CPUs productive.
Normal work stealing:
P0: [g1, g2, g3, g4] P1: [] (idle)
P1 tries to steal from P0 → always succeeds
P0: [g1, g2] P1: [g3, g4]
Our D&D modification:
P0: [g1, g2, g3, g4] P1: [] (idle)
P1 rolls d20: rolled 7 → failed! No steal.
P1 rolls d20: rolled 16 → success! Stole goroutines.
P0: [g1, g2] P1: [g3, g4]
Background: The stealWork Function
The work stealing logic lives in stealWork in proc.go. This function is called by findRunnable when a P has no local work. It loops up to 4 times over all Ps in a randomized order, trying to steal goroutines:
grep -n "func stealWork" go/src/runtime/proc.go
You’ll find stealWork around line 3828. Inside it, look for the runqsteal call:
grep -n "runqsteal" go/src/runtime/proc.go | head -5
The steal attempt looks like this (around line 3883–3887):
// Don't bother to attempt to steal if p2 is idle.
if !idlepMask.read(enum.position()) {
if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
return gp, false, now, pollUntil, ranTimer
}
}
Key variables at this point:
- pp — The current P (the thief), type *p, with field pp.id (int32)
- p2 — The target P (the victim), type *p, with field p2.id
- runqsteal(pp, p2, ...) — Moves goroutines from p2’s queue to pp’s queue; returns the first stolen goroutine
Step 1: Add the D&D Dice Roll Gate
Edit go/src/runtime/proc.go:
Find the steal attempt block (around line 3883–3887):
// Don't bother to attempt to steal if p2 is idle.
if !idlepMask.read(enum.position()) {
if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
return gp, false, now, pollUntil, ranTimer
}
}
Replace it with the dice-gated version:
// Don't bother to attempt to steal if p2 is idle.
if !idlepMask.read(enum.position()) {
if mainStarted && gogetenv("GODND") != "" {
// D&D Work Stealing: Roll a d20 to attempt stealing!
roll := cheaprandn(20) + 1 // Roll 1-20
if roll > 10 {
if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
println("[P", pp.id, "] Rolling to steal from P", p2.id, "... rolled", roll, ". Stole!")
return gp, false, now, pollUntil, ranTimer
}
} else {
println("[P", pp.id, "] Rolling to steal from P", p2.id, "... rolled", roll, ". Failed!")
}
} else {
if gp := runqsteal(pp, p2, stealTimersOrRunNextG); gp != nil {
return gp, false, now, pollUntil, ranTimer
}
}
}
Understanding the Code
mainStarted— A boolean inproc.gothat flips totrueonce the main goroutine is underway. This cuts out the very earliest scheduler noise during bootstrap, though some pre-main prints will still appear.gogetenv("GODND")— The runtime’s internal environment variable reader (equivalent toos.Getenv— the runtime cannot importos). Gates the dice rolling behindGODND=1so the scheduler runs normally unless you opt in.cheaprandn(20) + 1— Generates a d20 roll (1–20).cheaprandn(20)returns 0–19; the+1shifts to proper d20 range.roll > 10— 50% success rate: rolls 11–20 succeed, rolls 1–10 fail.println(...)— The runtime’s built-in print, writes directly to stderr with no imports needed.pp.id/p2.id— The processor ID fields (int32), defined in thepstruct inruntime2.go.- The “Stole!” message only prints when
runqstealreturns non-nil — the victim’s queue might have emptied between the idle check and the steal attempt.
Fun fact: The scheduler already rolls with advantage — four times!
Look at the outer loop in
stealWork:const stealTries = 4. The scheduler doesn’t just try to steal once — it loops 4 times over all Ps, re-shuffling the order withcheaprand()each pass. Your d20 gate gets rolled multiple times per P per “round.” In D&D terms, that’s rolling with advantage… twice over.The 4th pass is special: it sets
stealTimersOrRunNextG = true, which unlocks stealing the victim’srunnextslot — the goroutine the victim was about to run next. The source comment says “stealing from the other P’s runnext should be the last resort.” The final pass is the desperate, gloves-off round.The Go scheduler was already playing D&D before you got here. You’re just making the dice visible.
Step 2: Rebuild the Go Toolchain
cd go/src
./make.bash
Step 3: Create the Demo Program
Create dnd_steal_demo.go:
package main
import (
"runtime"
"sync"
)
func busyWork(id int, wg *sync.WaitGroup) {
defer wg.Done()
sum := 0
for i := 0; i < 1_000_000; i++ {
sum += i
}
println("Goroutine", id, "finished, sum =", sum)
}
func main() {
runtime.GOMAXPROCS(4) // 4 Ps for visible stealing
println("=== D&D Work Stealing Demo ===")
println()
var wg sync.WaitGroup
for i := 1; i <= 20; i++ {
wg.Add(1)
go busyWork(i, &wg)
}
wg.Wait()
println()
println("=== All goroutines completed! ===")
}
Step 4: Build and Run with D&D Mode
Build the binary first (without GODND=1 so the compiler’s own scheduling is silent):
../go/bin/go build -o dnd_steal_demo dnd_steal_demo.go
Then run with D&D mode enabled:
GODND=1 ./dnd_steal_demo
Expected output (varies every run due to randomness):
[P 1 ] Rolling to steal from P 0 ... rolled 15 . Stole!
=== D&D Work Stealing Demo ===
[P 2 ] Rolling to steal from P 0 ... rolled 3 . Failed!
[P 3 ] Rolling to steal from P 1 ... rolled 18 . Stole!
[P 2 ] Rolling to steal from P 0 ... rolled 9 . Failed!
[P 2 ] Rolling to steal from P 1 ... rolled 14 . Stole!
Goroutine 5 finished, sum = 499999500000
[P 0 ] Rolling to steal from P 3 ... rolled 7 . Failed!
[P 0 ] Rolling to steal from P 2 ... rolled 20 . Stole!
Goroutine 1 finished, sum = 499999500000
Goroutine 12 finished, sum = 499999500000
...
=== All goroutines completed! ===
[P %
You’ll see dice rolls interleaved with goroutine completion messages. Rolls of 1–10 fail, rolls of 11–20 succeed. A P with no work keeps retrying different victims until it rolls high enough!
Why are there dice rolls before
=== D&D Work Stealing Demo ===?You didn’t write those — the runtime did. Between
mainStartedflipping totrueand your firstprintln, the runtime startssysmon, enables the GC, and runsinit()functions — each spawning goroutines that idle Ps immediately try to steal. You’ve instrumented the scheduler itself, so you’re seeing activity that was always there, just silent.Why is there a truncated
[P %at the end?Same story, other end. After
wg.Wait()returns, idle Ps are still spinning instealWorklooking for more work. One starts aprintlnjust asmain()returns and the process exits — the print never finishes. The%is your shell saying the output didn’t end with a newline. The scheduler doesn’t stop for you on the way out.Welcome to the inside of Go!
Cleanup
To remove the dice roll gate:
cd go/src/runtime
git checkout proc.go
cd ..
./make.bash
Summary
You’ve turned Go’s work stealing scheduler into a tabletop RPG encounter:
Before: P tries to steal → always succeeds if target has work
After: P tries to steal → must roll > 10 on a d20 first (with GODND=1)
Changes: runtime/proc.go stealWork() function (~14 lines)
Result: The scheduler now plays D&D!
The underlying mechanism — stealWork, runqsteal, cheaprandn, stealTries = 4 — is real production Go code. You’ve just added a gate on top of it.
Continue to Exercise 10 or return to the main workshop