Go Routine
Ever wondered what actually happens under the hood when you type go func() in Golang? Many developers use Go routine daily, but few dive deep into the low-level OS and memory mechanics that make them so insanely efficient. Let me break down the real magic behind Go’s concurrency model!
What is Go routine?
A Go routine is a lightweight, logical, or virtual thread managed directly by the Go Runtime rather than the operating system kernel. In Go, prefixing any function call with the go keyword spawns a new Goroutine that runs concurrently alongside the rest of the program. Unlike traditional OS threads, which require a fixed memory stack of around 8 MB upon creation, a Goroutine starts with an initial stack size of only 2 KB.
How Goroutines Run at the OS and Memory Level?
—
1. Go Runtime as a Mini OS
When a compiled Go binary is executed, the host operating system loads it into RAM. Immediately inside the process, the Go Runtime boots up like a mini virtual operating system. This runtime initializes four core subsystems:
- Goroutine Scheduler (manages context switching and execution)
- Heap Allocator (manages memory allocation)
- Garbage Collector (GC) (cleans up unused memory)
- Logical Processors (virtual slots mapped to CPU cores)
Get Mohaiminul Ayon’s stories in your inbox
Join Medium for free to get updates from this writer.
2. Heap Allocation amp; Dynamic Growing Stacks
- Stack Location: The 2 KB stack for a Goroutine does not reside in the OS kernel’s thread stack area; it is dynamically allocated inside the applications RAM Heap memory.
- Growing Stack: If a Goroutine runs out of its initial 2 KB space (e.g., due to deep function calls or recursion), the Go Runtime automatically detects this, allocates a larger stack (e.g., 4 KB, 8 KB) on the heap, copies the existing stack data over, and deletes the old stack.
3. The M: N Scheduling Model
Go uses an M:N Scheduler model, where Goroutines are multiplexed onto OS threads :
- The Go Runtime inspects the physical CPU cores available and creates corresponding Logical Processors mapped to real OS threads.
-The Goroutine Scheduler distributes all active Goroutines across these logical processors
-If application workload grows drastically, the Go Runtime can dynamically adjust or request additional OS threads from the OS kernel, provided RAM is available.
4. Main Goroutine Lifecycle amp; Execution Order
-The Main Goroutine: The programs main() function executes inside a dedicated Main Goroutine
- Process Termination: If the Main Goroutine finishes its execution and exits, the Go Runtime immediately terminates the entire process. Any background Goroutines still running are instantly destroyed
- Non-Deterministic Execution: The order in which concurrent Goroutines execute is non-deterministic; it is entirely determined by the internal scheduling decisions of the Go Scheduler
If you want to learn more, please check this video — https://lnkd.in/guXH_spS




