Python Goroutines & The M:N Work-Stealing Scheduler
Goroutines are ultra-lightweight concurrent execution units multiplexed onto OS threads by the Go runtime. Learn the "go" keyword, the M:N scheduler model (G, M, P), and sync.WaitGroup coordination.
"Operating system threads are heavy 18-wheeler trucks. Goroutines are nimble electric scooters—you can launch 100,000 of them simultaneously on a laptop without running out of RAM."
Deep Dive: How It Works
The GMP Scheduler: Goroutines (G) are multiplexed onto OS threads (M) via logical processor contexts (P).
Dynamic 2KB Stacks: Goroutines start with only 2KB of memory and grow/shrink dynamically as required.
sync.WaitGroup: Coordinates termination of concurrent goroutines via Add(), Done(), and Wait().
Syntax Blueprint
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
doWork()
}()
wg.Wait()Increment WaitGroup counter with Add(1), execute task in goroutine with go keyword, defer Done(), and block with Wait().
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting to call wg.Wait() in main, causing program to exit before workers execute.Why it happens: Process termination exits all active goroutines instantly without waiting.
How to fix: Always call wg.Wait() before main returns.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Spawn 3 Concurrent Squarers
Use sync.WaitGroup to spawn 3 goroutines calculating squares of numbers 2, 4, 6.
Each goroutine should print "Square of [n]: [n*n]".
In main(), initialize wg, call wg.Add(3), launch goroutines with wg.Done(), and wait with wg.Wait().
Finished reading and practicing?
Mark this lesson as completed to update your course progress.