Exercise 8: Patient Go - Making the GMP Scheduler Wait for Goroutines
Want to learn more? Read The Go Runtime Scheduler on Internals for Interns for a deep dive into how Go’s GMP scheduling model works.
In this exercise, you’ll modify the Go runtime to wait for all goroutines to complete before the program exits. You’ll learn how runtime.main() orchestrates your program’s lifecycle and how the GMP scheduling model tracks goroutines.
Learning Objectives
By the end of this exercise, you will:
- Understand Go’s GMP (Goroutine, Machine, Processor) scheduling model
- Know how
runtime.main()inproc.gobootstraps and tears down your program - Modify the main runtime function to wait for all goroutines before exiting
- Understand the trade-offs of automatic goroutine waiting
Introduction: The GMP Model
Go’s scheduler maps lightweight goroutines onto OS threads using three abstractions:
- G (Goroutine): A lightweight execution unit with its own stack (starting at 2KB). Every
gostatement creates a new G. The runtime can manage millions of Gs. - M (Machine): An OS thread. Each M has a special
g0goroutine used for scheduler and runtime management tasks. The number of Ms can grow as needed (e.g., when goroutines block on syscalls). - P (Processor): A logical scheduling context. Each P holds a local run queue of runnable goroutines and a memory allocator cache. The number of Ps is controlled by
GOMAXPROCS(default: number of CPU cores).
The key insight: a goroutine runs when it is assigned to a P, which is running on an M. If all Ps are busy, new goroutines wait in the global run queue. If an M blocks on a syscall, its P is handed off to another M so work can continue.
The Bootstrap Sequence
A Go binary doesn’t start at your main(). The OS runs architecture-specific assembly (_rt0_amd64_linux or similar) which bootstraps the runtime:
- Assembly sets up the initial stack and calls
runtime.rt0_go rt0_goinitializes the scheduler, memory allocator, and GCruntime.main()is called as a goroutineruntime.main()starts the system monitor, enables GC, runsinit()functionsruntime.main()calls yourmain.main()via a linkname directive- When
main.main()returns,runtime.main()tears down the program
Step 6 is where we’ll intervene.
Background: Go’s Current Termination Behavior
When your main() returns, the program exits immediately — even if goroutines are still running:
package main
import "time"
func main() {
go func() {
time.Sleep(2 * time.Second)
println("Goroutine finished!")
}()
println("Main finished!")
// Program exits immediately — goroutine never prints
}
Current output:
Main finished!
The goroutine is simply abandoned. We’ll change this so Go waits for all goroutines:
New output:
Main finished!
Goroutine finished!
Step 1: Understand the Runtime Main Function
Open go/src/runtime/proc.go and find the main() function:
grep -n "^func main()" go/src/runtime/proc.go
Near the top of this function (around line 136–137), you’ll see how the runtime links to your program’s main:
//go:linkname main_main main.main
func main_main()
This //go:linkname directive tells the linker to bind the runtime’s main_main symbol to your program’s main.main function. This is how the runtime can call code in your main package from the runtime package.
Further down in the same main() function (around line 289), you’ll find where this is called:
fn := main_main // indirect call: linker doesn't know main package address at runtime layout time
fn()
// ... tear-down process follows
The tear-down starts immediately after fn() returns. That’s the point we’ll modify.
Step 2: Add Goroutine Waiting Logic
We’ll add a loop after fn() that yields the processor until only one goroutine remains — the main goroutine itself.
Edit go/src/runtime/proc.go:
Find the section around line 289–290 where main_main is called:
fn := main_main // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime
fn()
Add the waiting loop immediately after:
fn := main_main // make an indirect call, as the linker doesn't know the address of the main package when laying down the runtime
fn()
// Patient Go: wait until only the main goroutine is left
for gcount(false) > 1 {
Gosched()
}
Understanding the Code
gcount(false)— Returns the count of active (non-system) goroutines. Thefalseargument excludes background system goroutines like the GC worker and the network poller. When only the main goroutine remains, this returns 1.gcount(false) > 1— The condition: as long as other goroutines exist, keep waiting.Gosched()— Yields the current P, allowing the scheduler to run other goroutines. Without this, the loop would spin on the main goroutine and starve the others.- The loop exits when all user goroutines have finished, leaving just the main goroutine (count = 1). Then the normal tear-down proceeds.
Step 3: Rebuild the Go Toolchain
cd go/src
./make.bash
Step 4: Test Basic Goroutine Waiting
Create patient_demo.go:
package main
import "time"
func main() {
println("Main starting...")
go func() {
time.Sleep(1 * time.Second)
println("Goroutine 1 finished!")
}()
go func() {
time.Sleep(2 * time.Second)
println("Goroutine 2 finished!")
}()
println("Main finished, but Go will wait...")
}
Run with your modified Go:
../go/bin/go run patient_demo.go
Expected output:
Main starting...
Main finished, but Go will wait...
Goroutine 1 finished!
Goroutine 2 finished!
Go now waits patiently for all goroutines to complete before exiting.
Step 5: Test That Infinite Goroutines Hang
Patient Go has a notable consequence. Create infinite_demo.go:
package main
func main() {
go func() {
for {
// Infinite goroutine — never finishes
}
}()
println("Main done, waiting forever now...")
}
../go/bin/go run infinite_demo.go
Expected output:
Main done, waiting forever now...
…and the program hangs indefinitely. The infinite goroutine prevents the program from ever exiting. This is the main trade-off: patient Go cannot distinguish between a goroutine that’s still doing useful work and one that’s stuck.
Press Ctrl+C to kill it.
Step 6: Compare With sync.WaitGroup
The standard Go way to wait for goroutines is sync.WaitGroup. Show the comparison:
package main
import (
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
time.Sleep(1 * time.Second)
println("Goroutine 1 done")
}()
go func() {
defer wg.Done()
time.Sleep(2 * time.Second)
println("Goroutine 2 done")
}()
println("Main waiting explicitly...")
wg.Wait()
println("Main exiting after explicit wait")
}
With your modified Go, this works fine — main() waits via wg.Wait(), then returns, then the runtime’s new loop sees gcount == 1 and proceeds immediately. The explicit WaitGroup and the implicit runtime wait cooperate correctly.
Understanding the GMP Connection
The modification works because the GMP scheduler maintains an accurate count of all goroutines:
G1 (main goroutine) ─→ runs on P0 ─→ reaches fn(), calls main.main()
main.main() spawns G2, G3
main.main() returns
our loop: gcount(false) == 3, call Gosched()
G1 yields P0 ─────────→ scheduler picks G2 or G3 to run
...eventually...
G2 and G3 finish ──────→ gcount(false) == 1
G1 resumes ────────────→ loop exits → tear-down → exit
Gosched() is the critical ingredient: without yielding, the main goroutine would spin in a tight loop on the scheduler’s thread and never allow G2 or G3 to run. By calling Gosched(), G1 voluntarily gives up its P so the scheduler can run the waiting goroutines.
Cleanup
To restore standard Go termination behavior:
cd go/src/runtime
git checkout proc.go
cd ..
./make.bash
Summary
You’ve made Go patient:
Before: main() returns → immediate exit → goroutines abandoned
After: main() returns → wait for goroutines → all complete → exit
Changes: runtime/proc.go — added 3-line loop after fn() call
Result: No goroutine left behind (for finite goroutines)
This exercise revealed exactly how runtime.main() orchestrates program startup and teardown, and showed how the GMP model’s goroutine counter enables simple but powerful scheduler introspection.
Continue to Exercise 9 or return to the main workshop