Go's Goroutines: The 2KB Lightweight Concurrency Engine
Go's goroutines are lightweight, user-space threads managed by the Go runtime, starting with an initial stack size of only ~2KB. This M:N scheduling model (many goroutines on fewer OS threads) drastically reduces memory consumption and context switching overhead compared to traditional OS threads, which typically consume 1MB per thread.
The top 3
- Goroutines vs. OS Threads: 500x Less Memory, 70x Faster Switch: Goroutines start with only ~2KB stack space, allowing millions to run with minimal memory, whereas OS threads typically require ~1MB (Linux default); context switching a goroutine is ~70 times faster (around 54ns) than an OS thread's ~3.5 microseconds.
- Go's M:N Scheduler: Multiplexing Millions on Few OS Threads: Go's runtime employs an M:N scheduling model, efficiently mapping many (M) goroutines onto a smaller number (N) of OS threads, managing them in user space to reduce overhead and maximize CPU utilization by switching tasks on the same OS thread during I/O waits.
- Go Channels: Safely Communicating Between Goroutines: Go channels offer a synchronized, type-safe conduit for goroutines to send and receive data, effectively implementing the 'Don't communicate by sharing memory; share memory by communicating' principle to prevent race conditions.
Sources
Open the full topic