Patterns from Go
Go's runtime and standard library demonstrate clean, practical pattern implementations.
| Pattern | Where in Go | What It Does |
|---|---|---|
| Cooperative Scheduling | runtime/proc.go | Goroutine scheduling with cooperative preemption points |
| Bitmask | os/types.go | FileMode — Unix permission flags via typed constants with iota |
| Object Pool | sync/pool.go | sync.Pool — per-P local pools with lock-free fast path, used in fmt, encoding/json |
| Work Stealing | runtime/proc.go | stealWork — goroutine scheduler steals from other P's run queues via runqsteal/runqgrab |
| Free List | runtime/mfixalloc.go | fixalloc — fixed-size free-list allocator with intrusive mlink nodes |
| LRU Cache | groupcache lru/lru.go | Cache struct with doubly linked list + hash map, by Brad Fitzpatrick |
| Consistent Hashing | groupcache consistenthash.go | Hash ring with virtual nodes for distributed caching |
| Rate Limiter | x/time/rate | Token bucket rate limiter in the extended standard library |
| Semaphore | x/sync/semaphore | Weighted semaphore — used internally by errgroup for goroutine concurrency limiting |
| Flyweight | sync/pool.go | sync.Pool as flyweight — Get() returns a cached instance instead of allocating, Put() returns it for reuse |
| Arena Allocator | arena/arena.go | Experimental arena allocator — New[T]() allocates, Free() releases everything at once bypassing GC |
How They Compose: Goroutine Scheduling
When you launch go func(), multiple patterns work together to run millions of goroutines on a few OS threads:
go func() { ... }▼The runtime allocates goroutine stacks from a fixed-size allocator (fixalloc). No malloc/free per goroutine — just grab a node from the free list.
sync.Pool provides per-P local pools for temporary objects (like fmt buffers). Each P has a private pool → no lock contention.
The goroutine runs until it hits a preemption point (function call, channel op, or async preemption signal). Then the scheduler picks the next goroutine.
When a P's local run queue is empty, it steals goroutines from another P's queue. stealWork() grabs half the victim's queue in one batch, keeping all cores busy.
When goroutines need bounded concurrency (e.g., errgroup with limit), the weighted semaphore controls how many run at once.
The GMP model (Goroutines, M threads, P processors) is the glue: each P owns a local run queue, a free-list allocator, and a sync.Pool shard. Work stealing only kicks in when a P runs dry. This design means most operations are lock-free on the fast path, and contention only happens during stealing — which is the rare case by design.