NOTE

3.8 Golang Stack Management

What the stack is, Go stack characteristics, dynamic growth, contiguous vs segmented stacks, and references.

GoCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is the Stack?

  • Small space, with data stored for a relatively short time. The stack is at high addresses and grows from high addresses toward low addresses.
  • Allocation: automatically allocated on function calls.
  • Reclamation: automatically reclaimed when functions return.

2. Characteristics of the Golang Stack

2.1. Dynamic Growth

  • The Go runtime does not allocate a fixed amount of space to each goroutine; it dynamically allocates stack space as needed.

  • When a goroutine is created, it gets a small initial stack. The minimum stack size is 2 KB, while the actual allocation can be adjusted by the runtime for the platform. What happens when it is used up?

    • How is exhaustion detected? There is checking code at the beginning of a Go function.
    • How is the stack expanded? See contiguous stacks and segmented stacks.

2.2. Contiguous Stack vs Segmented Stack

  • Before Go 1.3, the stack structure used segmented stacks; afterward, contiguous stacks were used.
  • Segmented stack:
    • Growth: call runtime.morestack and runtime.newstack to create new stack space. Multiple stack spaces are linked through a doubly linked list.
    • Shrinking: call lessstack.
    • Problem: hot splitting. For example, a function called inside a loop repeatedly grows and shrinks the stack.
  • Contiguous stack:
    • Growth:
      1. Call runtime.newstack to initialize a new stack twice as large as the old stack.
      2. Call runtime.copystack to copy all contents from the old stack to the new stack.
      3. Redirect pointers that pointed to variables on the old stack to the new stack.
      4. Call runtime.stackfree to destroy and reclaim the old stack’s memory space.

3. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub