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,
syncandcontext. - 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
- Q149Explain the GMP model of the Go scheduler.
- Q150How does work stealing work, and in what order does a P look for work?
- Q151What does this print with GOMAXPROCS(1), and why?
- Q152What is preemption in Go? Explain cooperative vs. asynchronous preemption (Go 1.14).
- Q153What does this program do on Go 1.13 vs Go 1.14+?
- Q154How does a goroutine's stack grow? What changed from segmented to contiguous stacks?