Go

How is a goroutine different from an OS thread?

Question 148MediumGo 1.22 to 1.25

A goroutine is a function running concurrently and scheduled by the Go runtime in user space. An OS thread is scheduled by the kernel. The main differences:

  • Stack: a goroutine starts with a small stack that can grow (about 2 KB, and since Go 1.19 the start size adapts to average use). Stacks grow and shrink by copying. OS threads usually get a fixed stack of 1–8 MB.
  • Creation and switching: creating a goroutine costs a few hundred nanoseconds and a few KB. A goroutine switch saves only a few registers and does not enter the kernel. A thread switch goes through the kernel and costs much more.
  • Identity: goroutines have no public ID and no handle, so you cannot kill or join one directly. You coordinate them with channels, sync and context.
  • M:N multiplexing: many goroutines run on a small number of threads. The runtime moves them between threads when they block.

What the interviewer wants to hear: goroutines are cheap, but they still cost memory and scheduler work. Hundreds of thousands are fine. An unbounded number per request is a bug.

More on Goroutines & the Scheduler

All 35 Goroutines & the Scheduler questions