Runtime
Go language's runtime is the core infrastructure for Go program execution. It's responsible for managing program memory allocation, garbage collection, goroutine scheduling, system monitoring, and other key functions. Unlike other languages, Go's runtime is closely integrated with user code, which enables Go to achieve efficient concurrent programming and automatic memory management.
Core Components
Go runtime is mainly composed of the following core components:
GMP Scheduler
GMP scheduler is one of the most core components of Go runtime, responsible for reasonably scheduling a large number of goroutines to execute on limited system threads. GMP represents:
- G (Goroutine): Coroutine, Go's lightweight thread
- M (Machine): System thread, execution thread at the operating system level
- P (Processor): Processor, contains resources needed to run Go code
GMP scheduler's design enables Go to efficiently support thousands of concurrent goroutines, making it the cornerstone of Go language's high concurrency characteristics.
Memory Allocator
Go's memory allocator is responsible for managing heap memory allocation. Its design is deeply influenced by Google's TCMalloc. Main features include:
- Multi-level cache design to reduce lock contention
- Different allocation strategies based on object size
- Automatically decides whether objects are allocated on stack or heap
The memory allocator works closely with the garbage collector to achieve efficient memory management.
Garbage Collector
Go uses Concurrent Mark-Sweep garbage collection algorithm. Main features:
- Three-color marking algorithm
- Write barrier technology for concurrent collection
- Low latency, STW time mostly below 100 microseconds in most cases
Go's garbage collector has been optimized over the years to meet the performance requirements of most business scenarios.
System Monitor
System monitor (sysmon) is an independent monitoring thread, responsible for:
- Preempting long-running goroutines
- Checking if garbage collection needs to be triggered
- Monitoring system status and making corresponding adjustments
It runs continuously in the background, ensuring stable operation of Go programs.
Learning Suggestions
Recommended learning order for runtime knowledge:
- First learn GMP Scheduler, understand goroutine scheduling mechanism
- Then learn Memory Allocator, understand how memory is allocated
- Then learn Garbage Collector, understand how memory is recycled
- Finally learn System Monitor, understand runtime's background monitoring mechanism
