This Is What Actually Happens When You go func() in Golang
Ever wondered what really happens when you write
go func()in Go?
You’re not just spinning up a thread — you’re kicking off a beautifully orchestrated dance between the runtime scheduler, OS threads, and a clever bit of runtime black magic. And yet, it all feels so… simple.
Let’s crack open the hood of Golang and walk through the internals of how goroutines actually work. Spoiler: It’s not just a pthread_create() under the hood.
What Happens When You Write go func()?
Let’s start with a simple example:
func main() {
go sayHello()
time.Sleep(1 * time.Second) // give the goroutine time to run
}
func sayHello() {
fmt.Println("Hello from a goroutine!")
}
func main() {
go sayHello()
time.Sleep(1 * time.Second) // give the goroutine time to run
}
func sayHello() {
fmt.Println("Hello from a goroutine!")
}
Looks innocent, right? That go keyword makes it look like we’re just creating a background thread. But the internal machinery is doing a lot more.
Go’s Runtime: The Scheduler Triangle (G-M-P Model)
At the heart of Go’s concurrency is its M:N scheduler, meaning:
- G = Goroutine
- M = Machine (OS Thread)
- P = Processor (Logical Context for scheduling)
Goroutines (G)
↓↓↓↓↓
+-------------------+
| Processors (P) | Each P holds a local run queue of Gs
+-------------------+
↓↓↓↓↓
OS Threads (M)
Goroutines (G)
↓↓↓↓↓
+-------------------+
| Processors (P) | Each P holds a local run queue of Gs
+-------------------+
↓↓↓↓↓
OS Threads (M)
The Go runtime maps many goroutines (G) onto a limited number of processors (P), which are in turn executed on system threads (M). This architecture allows Go to schedule thousands of goroutines efficiently without exploding memory or CPU usage.
Step-by-Step: What Happens During go func()?
Let’s break it down:
1. Your Code Calls go sayHello()
This isn’t a direct function call. The Go compiler translates it into a runtime call to:
newproc(fnPointer, arguments)
newproc(fnPointer, arguments)
This is a runtime function that:
- Allocates a new
G(goroutine struct) - Copies the function pointer and arguments
- Pushes the goroutine onto the local run queue of the current
P
2. Scheduler Pushes G into a Run Queue
Every P has a local run queue (a FIFO slice). The new goroutine is appended here.
If that queue is full, the runtime may spill goroutines to a global queue. Work stealing happens when other Ps are idle — they try to steal half of the queue from a busy P.
3. An M Executes the Goroutine
The Go runtime ensures that each P is attached to a running OS thread (M).
The M pulls a G from the P‘s run queue and executes it. If there’s no work, it may park (sysmon kicks in), sleep, or steal work.
Goroutine Internals: What’s Inside a G
A G (goroutine) struct is surprisingly rich. It contains:
- Stack pointer and boundaries
- Program counter
- Status (
_Grunnable,_Grunning,_Gwaiting, etc.) - Pointers to defer and panic handlers
- Linked list pointers for queues
This gives Go full control over the lifecycle and scheduling of each goroutine.
And unlike OS threads, goroutines start with a tiny 2 KB stack, which can grow and shrink dynamically.
Goroutine Stack Growth:
[2 KB] → [4 KB] → [8 KB] → ... (as needed)
Goroutine Stack Growth:
[2 KB] → [4 KB] → [8 KB] → ... (as needed)
This dynamic growth makes it viable to spawn millions of goroutines.
Code Flow Diagram
Here’s a high-level diagram of what happens when you call go func():
go sayHello()
└─> runtime.newproc()
└─> allocate new G
└─> push to P's run queue
└─> M picks G from queue
└─> executes sayHello()” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
main.go
└─> go sayHello()
└─> runtime.newproc()
└─> allocate new G
└─> push to P's run queue
└─> M picks G from queue
└─> executes sayHello()
main.go
└─> go sayHello()
└─> runtime.newproc()
└─> allocate new G
└─> push to P's run queue
└─> M picks G from queue
└─> executes sayHello()
Real Example With Output
<button data-code="func main() {
for i := 0; i
func main() {
for i := 0; i < 3; i++ {
go func(i int) {
fmt.Printf("Worker %d startingn", i)
time.Sleep(time.Second)
fmt.Printf("Worker %d donen", i)
}(i)
}
time.Sleep(2 * time.Second)
}
func main() {
for i := 0; i < 3; i++ {
go func(i int) {
fmt.Printf("Worker %d startingn", i)
time.Sleep(time.Second)
fmt.Printf("Worker %d donen", i)
}(i)
}
time.Sleep(2 * time.Second)
}
Expected Output (not ordered):
Worker 0 starting
Worker 2 starting
Worker 1 starting
Worker 2 done
Worker 1 done
Worker 0 done
Worker 0 starting
Worker 2 starting
Worker 1 starting
Worker 2 done
Worker 1 done
Worker 0 done
You’ll notice the output is unordered — because scheduling is preemptive, and the goroutines are being handled independently.
What Can Go Wrong?
- Race conditions — just because it’s easy to spawn goroutines doesn’t mean you should share memory carelessly.
- Goroutine leaks — if a goroutine blocks forever (e.g., waiting on a channel that never sends), it wastes memory.
- Scheduler contention — spinning up millions of goroutines with tight loops can still starve others.
Use pprof, runtime.NumGoroutine(), and context cancellation to manage lifecycle well.
Benchmarks: How Cheap Are Goroutines?
Let’s run a quick benchmark vs. OS threads.
<button data-code="func BenchmarkGoroutines(b *testing.B) {
for i := 0; i < b.N; i++ {
done := make(chan bool)
go func() {
done <- true
}()
func BenchmarkGoroutines(b *testing.B) {
for i := 0; i < b.N; i++ {
done := make(chan bool)
go func() {
done <- true
}()
<-done
}
}
func BenchmarkGoroutines(b *testing.B) {
for i := 0; i < b.N; i++ {
done := make(chan bool)
go func() {
done <- true
}()
<-done
}
}
On my M1 Mac:
- ~200ns per goroutine create+run
- 10MB RAM for 1 million idle goroutines
Compare that to 1MB+ per OS thread. Massive win.
Key Learnings
go func()is a gateway to Go’s sophisticated M:N scheduler- Goroutines are tiny, cheap, and smart — not OS threads
- The runtime dynamically balances goroutines across OS threads
- Understanding
G,M,Pmakes debugging and tuning easier
Final Thoughts
The beauty of Go is that it feels simple, but under the surface, it’s a masterclass in systems programming. Every time you type go func(), you’re launching a mini process handled by a lean, efficient scheduler that’s designed to scale.
So the next time your app is spawning 100k goroutines? Just smile — Go’s runtime has your back.


