Runtime
Overview
The Go runtime provides:
- Task scheduling (goroutines)
- Memory management (heap, GC, stack growth)
- I/O multiplexing (network poller)
- Synchronization (channels, mutexes)
- Introspection & tooling (pprof, trace, metrics)
Scheduler (G–P–M model)
- Cooperative + preemptive runtime scheduler that balances goroutines across OS threads and cores efficiently.
- Multiplexes goroutines across OS threads.
Garbage Collector (GC)
- Fully integrated concurrent, parallel, tri-color mark-and-sweep collector.
- Targets low pause times (≤ 1 ms).
- Works with write barriers & safe points.
- Tightly coupled with scheduler (goroutines may be paused briefly for GC phases).
Memory Management
- Go runtime implements its own heap allocator (inspired by tcmalloc).
- Handles small/large object allocation, arenas, spans, free lists.
- Includes stack management — goroutines start with a small stack (a few KB) and grow/shrink automatically.
Channels and Concurrency Primitives
- Channels (chan) are implemented in the runtime, including send/recv queues and synchronization.
- Also sync.Mutex, sync.WaitGroup, sync.Cond, etc. are thin wrappers around runtime primitives.
Network Poller
- Multiplexes network I/O using epoll (Linux), kqueue (BSD/macOS), IOCP (Windows).
- Integrates with scheduler: goroutines blocked on I/O are parked until readiness events arrive.
Timers
- Built-in timer wheel / heap to implement time.After, time.NewTimer, time.Ticker.
- Scheduler wakes goroutines when timers expire.
Syscall & Cgo Handling
- Special handling of blocking syscalls: goroutine parks, thread detaches, another M runs.
- Cgo integration: runtime manages extra threads for foreign calls.
Runtime Services
- panic/recover system (stack unwinding, defer execution).
- reflection support (reflect depends on runtime type descriptors).
- type system metadata: every type has a runtime descriptor (method sets, size, alignment).
- map & slice internals: although exposed as language constructs, their implementation lives in the runtime.
Diagnostics & Introspection
- Built-in tracing/logging hooks (GODEBUG env vars like schedtrace, gctrace).
- Stack traces (runtime.Stack), goroutine dumps (runtime.NumGoroutine).
- Profiling & tracing tools (runtime/pprof, runtime/trace).
Initialization & Program Start
- Before the main.main() runs, the runtime initializes memory, GC, threads, modules, etc.
- Acts like a mini "kernel" for Go processes.