# runtime

`runtime` 套件讓程式與 Go 執行環境（runtime）互動：查詢平台與 CPU、控制排程與垃圾回收、讀取記憶體統計、取得呼叫堆疊資訊。

## 這個套件做什麼

每個 Go 程式都內含一個 runtime：負責排程 goroutine、配置記憶體、執行垃圾回收（garbage collection，GC，自動回收不再使用的記憶體）。平常你不需要碰它，但有時候需要問它問題或請它幫忙：

- 「這支程式跑在什麼作業系統、幾顆 CPU 上？」
- 「現在有幾個 goroutine？會不會有 goroutine 洩漏？」
- 「目前用了多少記憶體、GC 跑了幾次？」
- 「是誰呼叫了這個函式？」（寫 log 套件、錯誤追蹤時需要）

和相近套件的差別：

| 需求 | 套件 |
| --- | --- |
| 調整 GC 參數、印堆疊、讀取建置資訊 | [`runtime/debug`](/pkg-runtime-debug) |
| CPU／記憶體效能剖析 | [`runtime/pprof`](/pkg-runtime-pprof)、[`net/http/pprof`](/pkg-net-http-pprof) |
| 本頁 | 平台資訊、goroutine、GC、記憶體統計、呼叫者資訊 |

注意：本頁許多數值（CPU 數、作業系統、記憶體用量）依機器而異，範例輸出是本機 go1.26.0、darwin/arm64（10 核心）的結果。

## 匯入

```go
import "runtime"
```

## 常用 API

### GOOS、GOARCH 與 Version

- `runtime.GOOS`：作業系統，如 `linux`、`darwin`（macOS）、`windows`
- `runtime.GOARCH`：CPU 架構，如 `amd64`、`arm64`
- `runtime.Version()`：編譯這支程式的 Go 版本

`GOOS`、`GOARCH` 是常數，值在編譯時決定：交叉編譯（`GOOS=linux go build`）出來的執行檔，即使在 macOS 上看也是 `linux`。要依平台寫不同程式碼，通常改用檔名後綴（`file_linux.go`）或建置約束（`//go:build`），而不是在執行期判斷。

簽名：

```go
const GOOS string = goos.GOOS
const GOARCH string = goarch.GOARCH
func Version() string
```

範例：

```go
package main

import (
	"fmt"
	"runtime"
)

func main() {
	fmt.Println("GOOS:", runtime.GOOS)
	fmt.Println("GOARCH:", runtime.GOARCH)
	fmt.Println("Version:", runtime.Version())

	switch runtime.GOOS {
	case "windows":
		fmt.Println("路徑分隔字元是 \\")
	default:
		fmt.Println("路徑分隔字元是 /")
	}
}
```

輸出（依機器而異）：

```text
GOOS: darwin
GOARCH: arm64
Version: go1.26.0
路徑分隔字元是 /
```

### NumCPU 與 GOMAXPROCS

- `NumCPU()`：目前程序可用的邏輯 CPU 數
- `GOMAXPROCS(n)`：設定最多同時有幾個執行緒在跑 Go 程式碼，回傳舊值；`n < 1` 時只查詢不修改，所以 `GOMAXPROCS(0)` 是查詢的慣用寫法

預設值通常等於可用 CPU 數，一般不需要調整。Go 1.25 起，在 Linux 容器中預設值也會考慮 cgroup 的 CPU 配額限制，並且在配額變動時自動更新；呼叫 `GOMAXPROCS(n)` 或設定 `GOMAXPROCS` 環境變數會停止自動更新，`SetDefaultGOMAXPROCS()` 可以恢復。

簽名：

```go
func NumCPU() int
func GOMAXPROCS(n int) int
func SetDefaultGOMAXPROCS()
```

範例：

```go
package main

import (
	"fmt"
	"runtime"
)

func main() {
	fmt.Println("NumCPU:", runtime.NumCPU())
	fmt.Println("GOMAXPROCS:", runtime.GOMAXPROCS(0))

	old := runtime.GOMAXPROCS(2)
	fmt.Println("改成 2，舊值:", old)
	fmt.Println("目前:", runtime.GOMAXPROCS(0))

	runtime.SetDefaultGOMAXPROCS()
	fmt.Println("恢復預設:", runtime.GOMAXPROCS(0))
}
```

輸出（依機器而異，本機為 10 核心）：

```text
NumCPU: 10
GOMAXPROCS: 10
改成 2，舊值: 10
目前: 2
恢復預設: 10
```

用環境變數也能設定：`GOMAXPROCS=4 go run .`。

### NumGoroutine

回傳目前存在的 goroutine 數量，包含 `main` 本身。常用在測試或監控中檢查 goroutine 洩漏（goroutine leak，goroutine 永遠卡住不結束，觀念見 [取消與結束](/concurrency-cancellation)）：數量持續上升就要注意。

簽名：

```go
func NumGoroutine() int
```

範例：

```go
package main

import (
	"fmt"
	"runtime"
	"sync"
)

func main() {
	fmt.Println("開始:", runtime.NumGoroutine())

	stop := make(chan struct{})
	var wg sync.WaitGroup
	for range 3 {
		wg.Go(func() {
			<-stop
		})
	}
	fmt.Println("啟動 3 個後:", runtime.NumGoroutine())

	close(stop)
	wg.Wait()
	fmt.Println("全部結束後:", runtime.NumGoroutine())
}
```

輸出：

```text
開始: 1
啟動 3 個後: 4
全部結束後: 1
```

`wg.Go` 是 Go 1.25 起的寫法，見 [WaitGroup 與 Once](/sync-once-waitgroup)。

### GC 與 ReadMemStats

- `GC()`：立即執行一次垃圾回收，呼叫者會等到回收完成。正式程式幾乎不需要手動呼叫，主要用在測試與量測
- `ReadMemStats(&m)`：把記憶體統計填進 `MemStats` 結構

`MemStats` 常看的欄位：

| 欄位 | 意義 |
| --- | --- |
| `HeapAlloc` | 目前堆積（heap）上仍在使用的位元組數 |
| `TotalAlloc` | 程式啟動以來累計配置的位元組數（只增不減） |
| `Sys` | 從作業系統取得的總記憶體 |
| `NumGC` | 已完成的 GC 次數 |
| `Mallocs`、`Frees` | 累計配置與釋放的物件數 |

注意：`ReadMemStats` 會短暫暫停整個程式（stop-the-world），不適合高頻率呼叫。持續監控可改用 `runtime/metrics` 套件。GC 的觀念見 [記憶體與 GC](/perf-gc)。

簽名：

```go
func GC()
func ReadMemStats(m *MemStats)
```

範例：

```go
package main

import (
	"fmt"
	"runtime"
)

var keep [][]byte

func main() {
	var before, after runtime.MemStats
	runtime.ReadMemStats(&before)

	for range 100 {
		keep = append(keep, make([]byte, 1<<20))
	}

	runtime.GC()
	runtime.ReadMemStats(&after)

	grew := after.HeapAlloc - before.HeapAlloc
	fmt.Println("HeapAlloc 增加至少 100 MiB:", grew >= 100<<20)
	fmt.Println("TotalAlloc 只增不減:", after.TotalAlloc >= before.TotalAlloc)
	fmt.Println("GC 次數增加:", after.NumGC > before.NumGC)

	keep = nil
	runtime.GC()
	var freed runtime.MemStats
	runtime.ReadMemStats(&freed)
	fmt.Println("釋放後 HeapAlloc 變小:", freed.HeapAlloc < after.HeapAlloc)
}
```

輸出：

```text
HeapAlloc 增加至少 100 MiB: true
TotalAlloc 只增不減: true
GC 次數增加: true
釋放後 HeapAlloc 變小: true
```

實際的位元組數依機器與執行狀況而異，範例只印比較結果。

### Caller

回傳呼叫堆疊上某一層的資訊：程式計數器（pc）、原始檔路徑、行號。`skip` 為 0 表示呼叫 `Caller` 的函式本身，1 表示它的呼叫者，依此類推。最後一個回傳值 `ok` 為 false 代表取不到。

搭配 `FuncForPC(pc).Name()` 可以取得函式名稱。這是 log 套件印出「哪個檔案第幾行」的原理。

簽名：

```go
func Caller(skip int) (pc uintptr, file string, line int, ok bool)
func FuncForPC(pc uintptr) *Func
```

範例：

```go
package main

import (
	"fmt"
	"path/filepath"
	"runtime"
)

func where() string {
	pc, file, line, ok := runtime.Caller(1)
	if !ok {
		return "unknown"
	}
	name := runtime.FuncForPC(pc).Name()
	return fmt.Sprintf("%s:%d %s", filepath.Base(file), line, name)
}

func loadConfig() {
	fmt.Println("目前位置:", where())
}

func main() {
	fmt.Println("目前位置:", where())
	loadConfig()
}
```

輸出：

```text
目前位置: main.go:23 main.main
目前位置: main.go:19 main.loadConfig
```

`file` 是完整的絕對路徑，範例用 `filepath.Base` 只取檔名。

### Callers 與 CallersFrames

要取得整串呼叫堆疊時，用 `Callers` 把每一層的 pc 填進切片，再用 `CallersFrames` 轉成可讀的 `Frame`（含函式名稱、檔案、行號）。`Callers` 的 `skip` 中，0 是 `Callers` 自己、1 是呼叫 `Callers` 的函式。

用 `Frames.Next()` 逐一讀取，`more` 為 false 表示讀完。比起對每個 pc 呼叫 `FuncForPC`，`CallersFrames` 能正確處理被內聯（inline）的函式。

簽名：

```go
func Callers(skip int, pc []uintptr) int
func CallersFrames(callers []uintptr) *Frames
func (ci *Frames) Next() (frame Frame, more bool)
```

範例：

```go
package main

import (
	"fmt"
	"path/filepath"
	"runtime"
	"strings"
)

func trace() {
	pcs := make([]uintptr, 10)
	n := runtime.Callers(2, pcs)
	frames := runtime.CallersFrames(pcs[:n])
	for {
		f, more := frames.Next()
		if strings.HasPrefix(f.Function, "main.") {
			fmt.Printf("%s (%s:%d)\n", f.Function, filepath.Base(f.File), f.Line)
		}
		if !more {
			break
		}
	}
}

func handler() { trace() }

func router() { handler() }

func main() {
	router()
}
```

輸出：

```text
main.handler (main.go:25)
main.router (main.go:27)
main.main (main.go:30)
```

堆疊再往上還有 runtime 內部的函式（如 `runtime.main`），範例只印出 `main.` 開頭的部分。

### Goexit

結束目前的 goroutine：先執行該 goroutine 所有被 `defer` 的函式，然後結束，不影響其他 goroutine。它不是 panic，所以 `recover` 會回傳 nil。

`testing` 的 `t.FailNow`、`t.Fatal` 內部就是用 `Goexit` 結束測試函式。

注意：在 `main` goroutine 呼叫 `Goexit` 時，其他 goroutine 會繼續執行；若其他 goroutine 也都結束了，程式會因死結而崩潰。一般程式碼不要在 `main` 中呼叫。

簽名：

```go
func Goexit()
```

範例：

```go
package main

import (
	"fmt"
	"runtime"
)

func step(n int) {
	if n == 2 {
		fmt.Println("第 2 步失敗，結束這個 goroutine")
		runtime.Goexit()
	}
	fmt.Println("完成第", n, "步")
}

func main() {
	done := make(chan struct{})
	go func() {
		defer close(done)
		defer fmt.Println("defer 仍會執行")
		for i := 1; i <= 3; i++ {
			step(i)
		}
	}()
	<-done
	fmt.Println("main 繼續執行")
}
```

輸出：

```text
完成第 1 步
第 2 步失敗，結束這個 goroutine
defer 仍會執行
main 繼續執行
```

### AddCleanup

Go 1.24 起，`AddCleanup(ptr, cleanup, arg)` 註冊一個清理函式：當 `ptr` 指向的物件變得不可達（沒有任何地方再引用它）並被 GC 回收後，runtime 會在另一個 goroutine 中呼叫 `cleanup(arg)`。用來確保包裝外部資源（檔案描述符、C 記憶體）的物件被遺忘時，資源仍會被釋放。

它取代較舊的 `SetFinalizer`，更不容易誤用。回傳的 `Cleanup` 可以呼叫 `Stop()` 取消，例如使用者已經手動 `Close` 的時候。

注意：

- `arg` 不能是 `ptr` 本身（會 panic），`cleanup` 與 `arg` 也不能引用到 `ptr`，否則物件永遠不會被回收
- 執行時機不保證，程式結束前也可能完全不執行。必要的釋放動作仍要提供明確的 `Close` 方法，`AddCleanup` 只當保險

簽名：

```go
func AddCleanup[T, S any](ptr *T, cleanup func(S), arg S) Cleanup
func (c Cleanup) Stop()
```

範例：

```go
package main

import (
	"fmt"
	"runtime"
	"time"
)

type Conn struct {
	id  int
	buf []byte
}

func open(id int, released chan<- int) *Conn {
	c := &Conn{id: id, buf: make([]byte, 1024)}
	runtime.AddCleanup(c, func(id int) {
		released <- id
	}, id)
	return c
}

func main() {
	released := make(chan int, 1)
	c := open(7, released)
	fmt.Println("使用連線", c.id)
	c = nil

	runtime.GC()
	select {
	case id := <-released:
		fmt.Println("連線", id, "的資源已釋放")
	case <-time.After(time.Second):
		fmt.Println("清理尚未執行")
	}
}
```

輸出：

```text
使用連線 7
連線 7 的資源已釋放
```

清理函式收到的是 `arg`（這裡是 `id`），而不是 `Conn` 本身，因為那時物件已經被回收了。

## 重點整理

- `GOOS`、`GOARCH` 是編譯時決定的常數；`Version()` 回傳編譯用的 Go 版本
- `NumCPU()` 查 CPU 數，`GOMAXPROCS(0)` 查目前設定；預設值通常就是最佳值（Go 1.25 起會考慮容器 CPU 配額）
- `NumGoroutine()` 可用來偵測 goroutine 洩漏
- `ReadMemStats` 讀記憶體統計但會短暫停止程式；`GC()` 主要用於測試與量測
- `Caller`、`Callers`＋`CallersFrames` 取得呼叫者與堆疊資訊
- `AddCleanup`（Go 1.24 起）取代 `SetFinalizer`，但只當保險，資源仍要明確關閉

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：runtime](https://pkg.go.dev/runtime)
- [Go 1.26.0 原始碼：src/runtime](https://github.com/golang/go/tree/go1.26.0/src/runtime)
