Sobes.tech
Middle+

How are goroutines structured and how much memory do they occupy in the stack?

sobes.tech AI

Answer from AI

A goroutine is a lightweight thread of execution managed by the Go runtime environment. They are multiplexed onto a smaller number of system threads (thread pool).

Main components:

  • Stack: Each goroutine has its own, expandable stack. Initially small (16KB with Go 1.4+, previously 8KB), it can grow or shrink as needed.
  • Go Scheduler: Implements the M:N model (M goroutines on N system threads). It is responsible for scheduling goroutines on available system threads. Switching occurs during blocking operations (I/O, channel wait) or explicit calls to runtime.Gosched().
  • Context: Contains a pointer to the machine code for execution, a stack pointer, and other metadata required by the scheduler.

The initial size of a goroutine's stack with Go 1.4 is 16KB. This size is not fixed and can change dynamically.