← 中文资源

简体中文版本

runtime.Stack 转储 goroutine 堆栈

runtime.Stack 把当前 goroutine 的调用栈写进调用方缓冲,all=true 则转储全部 goroutine,是健康检查与崩溃诊断的轻量探针。

阅读英文原文

实现说明

runtime.Stack 转储 goroutine 堆栈可以归结为函数 main。

使用要点

  • 每一步打印都带着自己的标签:stack bytes:、all goroutines bytes:。

常见问题

运行「runtime.Stack 转储 goroutine 堆栈」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 stack bytes:、all goroutines bytes: 标签标明各步骤。

核心语句

buf := make([]byte, 4096)
all := make([]byte, 8192)

代码示例

package main

import (
	"fmt"
	"runtime"
)

func main() {
	buf := make([]byte, 4096)
	// Stack dumps the calling goroutine's traces into the buffer
	n := runtime.Stack(buf, false)
	fmt.Printf("stack bytes: %d\n", n)

	// all=true walks every goroutine: useful for health diagnostics
	all := make([]byte, 8192)
	total := runtime.Stack(all, true)
	fmt.Printf("all goroutines bytes: %d\n", total)

	// the dump always begins with the goroutine header
	fmt.Println(string(buf[:16]))
}