Fundamentals 11 min read

Understanding Go Stack Memory Management: Initialization, Allocation, Expansion, and Shrinking

This article explains how Go's runtime initializes, allocates, expands, and shrinks goroutine stack memory, detailing the underlying heap structures, global pools, platform‑specific constants, and the code paths that handle stack growth and reclamation.

Xueersi Online School Tech Team
Xueersi Online School Tech Team
Xueersi Online School Tech Team
Understanding Go Stack Memory Management: Initialization, Allocation, Expansion, and Shrinking

Introduction: Go's concurrency relies on lightweight goroutine stacks; this article examines the initial stack size and how the Go 1.12.5 runtime manages stack memory.

Heap memory management: Goroutine stacks are allocated from the heap using structures mspan, mcache, mcentral, and mheap.

Global stack initialization: The runtime.stackinit() function creates two global pools, stackpool and stackLarge, with platform‑specific size constants.

Memory allocation: When a new goroutine is created, newproc1 calls malg, which rounds the requested size, allocates memory via stackalloc, and sets guard pages.

Stack allocation details: func stackalloc(n uint32) stack distinguishes small and large stacks, obtains memory from the per‑P cache or the global stackpool, and falls back to the heap when necessary.

Pool refill and caching: Functions stackpoolalloc, stackcacherefill, and related code manage free lists and cache stacks for reuse.

Stack growth: When a goroutine exceeds its current stack, the runtime invokes runtime.morestack_noctxt and runtime.newstack, which double the stack size until a limit is reached.

Stack shrinking: The garbage collector may shrink a stack via shrinkstack, halving it when usage falls below a quarter of the allocated space.

Conclusion: The article outlines the initialization, allocation, expansion, and shrinking mechanisms of Go stack memory, providing code excerpts and diagrams to aid understanding.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

concurrencyGoStackGoroutine
Xueersi Online School Tech Team
Written by

Xueersi Online School Tech Team

The Xueersi Online School Tech Team, dedicated to innovating and promoting internet education technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.