Skip to content

Patterns from Go

Go's runtime and standard library demonstrate clean, practical pattern implementations.

PatternWhere in GoWhat It Does
Cooperative Schedulingruntime/proc.goGoroutine scheduling with cooperative preemption points
Bitmaskos/types.goFileMode — Unix permission flags via typed constants with iota
Object Poolsync/pool.gosync.Pool — per-P local pools with lock-free fast path, used in fmt, encoding/json
Work Stealingruntime/proc.gostealWork — goroutine scheduler steals from other P's run queues via runqsteal/runqgrab
Free Listruntime/mfixalloc.gofixalloc — fixed-size free-list allocator with intrusive mlink nodes
LRU Cachegroupcache lru/lru.goCache struct with doubly linked list + hash map, by Brad Fitzpatrick
Consistent Hashinggroupcache consistenthash.goHash ring with virtual nodes for distributed caching
Rate Limiterx/time/rateToken bucket rate limiter in the extended standard library
Semaphorex/sync/semaphoreWeighted semaphore — used internally by errgroup for goroutine concurrency limiting
Flyweightsync/pool.gosync.Pool as flyweight — Get() returns a cached instance instead of allocating, Put() returns it for reuse
Arena Allocatorarena/arena.goExperimental 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() { ... }
1
Free List

The runtime allocates goroutine stacks from a fixed-size allocator (fixalloc). No malloc/free per goroutine — just grab a node from the free list.

2
Object Pool

sync.Pool provides per-P local pools for temporary objects (like fmt buffers). Each P has a private pool → no lock contention.

3
Cooperative Scheduling

The goroutine runs until it hits a preemption point (function call, channel op, or async preemption signal). Then the scheduler picks the next goroutine.

4
Work Stealing

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.

5
Semaphore

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.

Further Reading

Released under the MIT License.