Exercise 12: Predictable Select - Making Select Statements Deterministic
Want to learn more? Read The select Statement on Internals for Interns for a deep dive into how Go’s
selectstatement works under the hood.
In this exercise, you’ll modify Go’s select statement to always pick the first ready case instead of choosing randomly. You’ll discover why Go randomizes select by default, where that randomization lives, and what you lose when you remove it.
Learning Objectives
By the end of this exercise, you will:
- Understand how Go’s
selectstatement is implemented in the runtime - Know the role of
pollorderandlockorderin case selection - Modify the runtime’s channel selection algorithm to be deterministic
- Observe the fairness implications of both approaches
Introduction: How Does Select Work Internally?
The select statement is implemented in selectgo() in runtime/select.go. When your code reaches a select with multiple cases, the runtime must decide which ready case to execute. It does this using two arrays:
pollorder: Determines the order in which cases are checked for readiness. By default, this order is randomized usingcheaprandn()so no single channel gets permanent priority.lockorder: Determines the order in which channel locks are acquired. This is sorted by channel address to prevent deadlocks — always acquiring locks in the same order avoids lock ordering cycles.
The runtime shuffles cases into pollorder, then iterates through them. If a case’s channel is ready (has data to receive or buffer space to send), that case executes. If no case is ready and there’s a default, the default runs. Otherwise, the goroutine parks itself on all the channels’ wait queues until one becomes ready.
The randomization in pollorder is deliberate: running the same select with all channels ready will pick different cases each time. This prevents programs from accidentally depending on case ordering, and ensures fairness — no channel starves.
Background: Go Randomizes Select
// All three channels are ready — who wins?
select {
case v := <-ch1: // Sometimes chosen
case v := <-ch2: // Sometimes chosen
case v := <-ch3: // Sometimes chosen
}
// Random selection prevents any one channel from starving the others
We’ll make it deterministic — always picking the first ready case:
select {
case v := <-ch1: // ALWAYS chosen when ready
case v := <-ch2: // Only if ch1 not ready
case v := <-ch3: // Only if ch1 and ch2 not ready
}
Step 1: See the Current Randomization
Create random_select_demo.go:
package main
func main() {
ch1 := make(chan int, 1)
ch2 := make(chan int, 1)
ch3 := make(chan int, 1)
// Fill all channels so they're all ready simultaneously
ch1 <- 1
ch2 <- 2
ch3 <- 3
// Run select 10 times — observe which case wins each time
for i := 0; i < 10; i++ {
select {
case v := <-ch1:
println("Round", i, ": Selected ch1 (value", v, ")")
ch1 <- 1 // Refill
case v := <-ch2:
println("Round", i, ": Selected ch2 (value", v, ")")
ch2 <- 2 // Refill
case v := <-ch3:
println("Round", i, ": Selected ch3 (value", v, ")")
ch3 <- 3 // Refill
}
}
}
Run with standard Go to see the randomization:
go run random_select_demo.go
Expected output (varies each run):
Round 0: Selected ch3 (value 3)
Round 1: Selected ch1 (value 1)
Round 2: Selected ch2 (value 2)
Round 3: Selected ch3 (value 3)
Round 4: Selected ch1 (value 1)
Round 5: Selected ch2 (value 2)
Round 6: Selected ch3 (value 3)
Round 7: Selected ch1 (value 1)
Round 8: Selected ch2 (value 2)
Round 9: Selected ch1 (value 1)
Each run produces a different sequence. All three channels get selected roughly equally — this is the fairness property.
Step 2: Navigate to the Select Implementation
cd go/src/runtime
The select.go file contains the entire select statement implementation. The key function is selectgo().
Step 3: Find the Randomization Code
grep -n "cheaprandn" go/src/runtime/select.go
You’ll find the shuffle around line 191 in select.go. It looks like this:
// go/src/runtime/select.go (around line 191)
j := cheaprandn(uint32(norder + 1)) // Random index
pollorder[norder] = pollorder[j]
pollorder[j] = uint16(i)
norder++
This is a Fisher-Yates shuffle applied as each case is added to pollorder:
cheaprandn(uint32(norder + 1))generates a random indexjin[0, norder]- The new case
iis placed at positionj, displacing whatever was there to the end - The result is a uniformly random permutation of all cases
Step 4: Make Select Deterministic
Edit go/src/runtime/select.go:
Find the randomized shuffle (the 3-line block above) and replace it with a deterministic assignment:
// Original randomized shuffle:
j := cheaprandn(uint32(norder + 1))
pollorder[norder] = pollorder[j]
pollorder[j] = uint16(i)
norder++
// Replace with deterministic source-order assignment:
pollorder[norder] = uint16(len(scases) - 1 - i)
norder++
Understanding the Code Change
The compiler (cmd/compile/internal/walk/select.go) places receive cases into scases in reverse source order: the first receive case in your code gets the highest index, the last gets the lowest. Concretely, for a 3-receive select the compiler assigns:
scases[2] = ch1 (first receive in source, index = ncas - 1)
scases[1] = ch2 (second receive in source, index = ncas - 2)
scases[0] = ch3 (third receive in source, index = ncas - 3)
The formula len(scases) - 1 - i undoes this reversal. As the loop iterates i = 0, 1, 2, it generates pollorder entries [2, 1, 0]. When selectgo scans pollorder forward, it visits:
pollorder[0] = 2 → scases[2] = ch1 ← checked first
pollorder[1] = 1 → scases[1] = ch2
pollorder[2] = 0 → scases[0] = ch3
- Result:
pollordervisits cases in their original source code order - Effect: The first ready case in source code order always wins
Step 5: Rebuild the Go Toolchain
cd ../ # back to go/src
./make.bash
Step 6: Test Deterministic Behavior
Run the same demo with your modified Go:
../go/bin/go run random_select_demo.go
Expected output (identical every run):
Round 0: Selected ch1 (value 1)
Round 1: Selected ch1 (value 1)
Round 2: Selected ch1 (value 1)
Round 3: Selected ch1 (value 1)
Round 4: Selected ch1 (value 1)
Round 5: Selected ch1 (value 1)
Round 6: Selected ch1 (value 1)
Round 7: Selected ch1 (value 1)
Round 8: Selected ch1 (value 1)
Round 9: Selected ch1 (value 1)
ch1 wins every round. It appears first in the source code, so it always has priority.
Step 7: Observe Channel Starvation
The fairness property is gone. Create starvation_demo.go to see the consequence:
package main
func main() {
ch1 := make(chan int, 1000)
ch2 := make(chan int, 1000)
ch3 := make(chan int, 1000)
// Pre-fill all channels so they're all ready simultaneously
for i := 0; i < 1000; i++ {
ch1 <- 1
ch2 <- 2
ch3 <- 3
}
counts := [4]int{}
for i := 0; i < 1000; i++ {
select {
case v := <-ch1:
counts[v]++
case v := <-ch2:
counts[v]++
case v := <-ch3:
counts[v]++
}
}
println("ch1 selected:", counts[1], "times")
println("ch2 selected:", counts[2], "times")
println("ch3 selected:", counts[3], "times")
}
Run with standard Go:
go run starvation_demo.go
Expected output (approximately equal distribution):
ch1 selected: 324 times
ch2 selected: 337 times
ch3 selected: 339 times
Now run with your modified Go:
../go/bin/go run starvation_demo.go
Expected output (ch1 dominates completely):
ch1 selected: 1000 times
ch2 selected: 0 times
ch3 selected: 0 times
With deterministic select, ch1 is checked first every time. All three channels are full at the start of each iteration, but only ch1 is ever selected. ch2 and ch3 never get a chance. This is starvation — a classic concurrency bug.
Why use pre-filled channels instead of goroutines? A version with goroutine producers (
go producer(ch1, 1)) would also show starvation, but goroutine scheduling introduces timing non-determinism: the exact counts vary by run and depend on how quickly the OS schedules each producer relative to the consumer. Pre-filling eliminates this noise — all channels are provably ready every iteration, so the select’s decision is the only variable.
Understanding What We Changed
selectgo() internals:
Original (random):
pollorder = shuffle([case0, case1, case2])
→ might produce [case2, case0, case1]
→ case2 checked first this round
Modified (deterministic):
pollorder = [case0, case1, case2] (always)
→ case0 is always checked first
→ case0 wins whenever it's ready
The randomization is not an implementation detail — it’s a correctness guarantee. Without it, any select where one channel is consistently ready will permanently starve the others.
Real-World Implications
Go’s spec explicitly says:
“If one or more of the communications can proceed, a single one that can proceed is chosen via a uniform pseudo-random selection.”
This is a language specification guarantee, not just a runtime implementation choice. Programs that depend on select being fair are correct by spec. Programs that depend on select having a particular order are incorrect by spec.
Your modified Go breaks this guarantee, which is why it’s fun for a workshop but would never ship.
Cleanup
To restore Go’s original random select behavior:
cd go/src/runtime
git checkout select.go
cd ..
./make.bash
Summary
You’ve transformed Go’s select from a fair, random chooser into a deterministic priority queue:
// Before: Random selection (fair — no starvation)
select {
case <-ch1: // ~33% chance when all ready
case <-ch2: // ~33% chance when all ready
case <-ch3: // ~33% chance when all ready
}
// After: Deterministic selection (predictable — but starves lower-priority channels)
select {
case <-ch1: // Always chosen when ready — 100% priority
case <-ch2: // Only if ch1 not ready — starved when ch1 is busy
case <-ch3: // Only if ch1 and ch2 not ready — almost never runs
}
Changes: runtime/select.go selectgo() — 3-line shuffle → 2-line deterministic assignment
Result: Source order wins, fairness lost, starvation introduced
This exercise showed that Go’s randomization is a correctness property baked into the language specification, not just a performance optimization.
Continue to Exercise 13 or return to the main workshop