Skip to content

Golang Goroutine Model

From Effective Go

They're called goroutines because the existing terms—threads, coroutines, processes, and so on—convey inaccurate connotations. A goroutine has a simple model: it is a function executing concurrently with other goroutines in the same address space. It is lightweight, costing little more than the allocation of stack space. And the stacks start small, so they are cheap, and grow by allocating (and freeing) heap storage as required.

Goroutines are multiplexed onto multiple OS threads so if one should block, such as while waiting for I/O, others continue to run. Their design hides many of the complexities of thread creation and management.

https://go.dev/doc/effective_go#goroutines

  1. 因為 Thread, Coroutine 或 Process 皆無法準確表達,所以造了一個新的詞:Goroutine
  2. Goroutine 們在同一個記憶體位置協作。
  3. 只比 Stack 使用多一點點記憶體。

G-M Model

G: Goroutine

M: Machine (實際上是 Thread)

  1. 每一個 M 有自己的 G Queue。
  2. 每個 G 都會輪流跑一小段時間,然後換其他 G 來跑。
  3. 當 M 本身的 G Queue 是空的話,就去偷其他 Queue 的 G 來跑 (Global Queue 優先,然後是其他 Queue)。

CAUTION

😱 假如有 G 遇到 io-block 事件呢? M 就會卡住。

G-P-M Model

P: Processor

G 和 M 中間多了一個 P。

Reference

goroutine 调度器原理

Scalable Go Scheduler Design Doc

Goroutine 與 Golang Runtime Scheduler

Changelog

Just observe 👀