COSCUP 2020 - Goroutine stack and local variable allocation in Go
Q&A 補充
Slides: Goroutine stack and local variable allocation in Go
這次分享中,有人詢問我在 stack growing 的時候, user stack 和 system stack 是如何交替切換的。由於當時沒有仔細看 switch 流程,無法很清楚地答覆他,所以事後又看了一下這段,並且畫出簡圖:

首先,在 curg (current goroutine) func1 呼叫 func2 後,發現 user stack 空間不足,此時先儲存 func1 的 state 到 M 的 morebuf struct 中(用來 bug tracing),接著把 func2 的 state (就是當前 goroutine 的執行狀態,包含 stack pointer, program counter 等)存在 curg 的 sched struct 中,接著 switch 到 g0,從 g0 的 sched 取出 stack pointer 的值 (system stack) 並且設定,接著就可以執行 newstack function。