owned this note changed 5 years ago
Linked with GitHub

Goroutine stack and local variable allocation in Go - Cherie Hsieh

tags: COSCUP2020 進階 TR214

歡迎來到 https://hackmd.io/@coscup/2020 共筆

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

點擊本頁上方的 開始用 Markdown 一起寫筆記!
手機版請點選上方 按鈕展開議程列表。

Slides: Goroutine stack and local variable allocation in Go

Run time stack

以 linux 來說,有分成 kernel stack 和 user stack
之後會著重在 user stack

在執行程式時,user stack 會含有 stackframe
大概含有

  • local variable
  • return address
  • etc.

User stack in C

heap, stack, data, text

當產生一個新的 thread 後,會在 user stack 找一塊空間當作 stack

main program 預設的 stack size 是 8K,可修改系統設定去修改
thread 是透過 clone syscall 去設定新的 stack 空間

User stack in Go

type stack struct {
    lo uintptr
    hi uintptr
}

type g struct {
    stack stack
}

Processor 下有 mcachemcache 又有 stackcache
stackcache 去拿取新的 stack 空間

stackcache 會從 stack pool (全域需加鎖) ,stack pool 又從 mhead

System stack in Go

在 GMP model 中的每個 M 會有一個 System stack

根據講者的圖,該 system stack 會對到 C 的 memory layout 中的 stack ?

預設大小也是 8K

stack growing mechanism

當超過常數 StackSmall = 128 byte,才會觸發 stack extension
當超過常數 StackBig = 4096 byte

當直接分配新空間,並複製原本的內容到新空間,會遇到一個問題
因為原本有些變數是指到舊的 stack 空間,直接複製會有問題
go 透過另外一個 map 去解決

那會不會 stack overflow

答案是: 會

當初始化 stack 時, stackframe 就超過 2K

直接失敗

Select a repo