NOTE
3.8 Golang Stack Management
What the stack is, Go stack characteristics, dynamic growth, contiguous vs segmented stacks, and references.
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.morestackandruntime.newstackto 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.
- Growth: call
- Contiguous stack:
- Growth:
- Call
runtime.newstackto initialize a new stack twice as large as the old stack. - Call
runtime.copystackto copy all contents from the old stack to the new stack. - Redirect pointers that pointed to variables on the old stack to the new stack.
- Call
runtime.stackfreeto destroy and reclaim the old stack’s memory space.
- Call
- Growth:
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub