Middle+
What is a goroutine? How does it differ from an OS thread? Who manages goroutines?
sobes.tech AI
Answer from AI
A goroutine is a lightweight thread of execution in the Go language, managed by the Go runtime rather than the operating system. Unlike OS threads, goroutines use much less memory (usually a few kilobytes of stack, which can grow and shrink dynamically), and their creation and switching are much cheaper in terms of resources.
Main differences from OS threads:
- Goroutines are scheduled and managed by the Go runtime, not the OS.
- There can be thousands or even tens of thousands of goroutines in a single process without significant load.
- Context switching between goroutines is faster because it does not require kernel switching.
Goroutine management is handled by the Go runtime, which contains its own scheduler (M:N scheduler), mapping many goroutines (G) onto fewer OS threads (M). This allows efficient use of system resources and simplifies parallel programming.