实现说明
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]))
}