08 / 10

What is a goroutine, and how does it differ from an OS thread?

Goroutines are lightweight user-space threads managed by the Go runtime, starting at ~2KB of stack and multiplexed onto a small pool of OS threads through the M:N scheduler.

Goroutines vs OS threads
  1. 1

    OS thread stack: 1-8MB fixed. Goroutine stack: starts at 2KB, grows and shrinks dynamically up to 1GB

  2. 2

    Context switch: OS thread switch requires kernel mode transition (~1μs). Goroutine switch is in user space (~100ns)

  3. 3

    Creation cost: spawning an OS thread takes ~10-100μs. Launching a goroutine takes ~1μs

  4. 4

    Scheduling: OS scheduler is preemptive and unaware of Go semantics. Go scheduler is cooperative with preemption at safe points

  5. 5

    Scale: practical limit for OS threads is ~10,000. Go programs routinely run 100,000+ goroutines

Goroutine basics