golang 如何查看程序的Goroutine个数


在 Go 程序中,有多种方法可以查看当前运行的 Goroutine 数量,以下是几种常见的方式:


1. 使用 runtime.NumGoroutine()

Go 的 runtime 包提供了 NumGoroutine() 函数,可以直接获取当前程序的 Goroutine 数量:

package main

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

func main() {
    for i := 0; i < 10; i++ {
        go func() {
            time.Sleep(time.Second)
        }()
    }

    // 获取当前 Goroutine 数量
    num := runtime.NumGoroutine()
    fmt.Println("Current Goroutines:", num) // 输出: 11 (main + 10 个后台 goroutine)
}

注意:

  • 返回的数量包括 主 Goroutine(main())和所有后台 Goroutine。
  • 如果 Goroutine 尚未被调度执行,可能不会立即反映在计数中。

2. 使用 pprof 监控

通过 net/http/pprof 可以实时查看 Goroutine 数量及堆栈信息:

package main

import (
	"net/http"
	_ "net/http/pprof" // 自动注册 pprof 路由
)

func main() {
    go http.ListenAndServe(":6060", nil) // 启动 pprof 服务

    // ... 你的业务代码 ...
}

访问 http://localhost:6060/debug/pprof/goroutine 可查看详细 Goroutine 信息。


3. 使用 debug 包打印堆栈

通过 runtime/debug 打印所有 Goroutine 的堆栈:

package main

import (
	"runtime/debug"
	"fmt"
)

func main() {
    debug.SetTraceback("all")
    stack := debug.Stack()
    fmt.Printf("Goroutine stacks:\n%s\n", stack)
}

这会输出所有 Goroutine 的调用栈,但需要手动解析数量。


4. 第三方工具

  • gops:Google 提供的工具,可查看进程的 Goroutine 数量:
    gops <PID>      # 查看指定进程信息
    
  • Prometheus + Grafana:通过 client_golang 暴露 Goroutine 指标进行监控。

关键注意事项

  1. Goroutine 泄漏:
    如果 NumGoroutine() 返回的数字持续增长,可能存在 Goroutine 泄漏(未正确关闭通道或未调用 cancel())。
  2. 并发安全:
    runtime.NumGoroutine() 是线程安全的,但返回的值可能瞬间变化。

总结

方法 适用场景 复杂度
runtime.NumGoroutine() 简单获取当前数量 低
pprof 详细分析 Goroutine 堆栈和泄漏 中
debug.Stack() 调试时打印所有堆栈 高

推荐在开发阶段结合 pprof 监控,生产环境通过 runtime.NumGoroutine() 定期日志记录。

posted @ 2025-04-09 16:01  morty-root  阅读(394)  评论(0)    收藏  举报