美文网首页Tips
Go 语言如何控制 goroutine 的数量并通过 pprof

Go 语言如何控制 goroutine 的数量并通过 pprof

作者: Sun东辉 | 来源:发表于2022-05-14 00:15 被阅读0次

Go 语言中,通常使用 channel 控制 goroutine 的数量,这里引入 sync.WaitGroup 是为了协程同步。

package main

import (
    "log"
    "net/http"
    "runtime"
    "sync"
    "time"

    _ "net/http/pprof"
)
func main() {
    concurrent := 5 // 控制 channel 缓存区的长度
    w := sync.WaitGroup{}
    ch := make(chan bool, concurrent)
    i := 0
    for {
        i++
        ch <- true
        w.Add(1)
        go func(i int) {
            defer w.Done()
            log.Println(http.ListenAndServe("localhost:6060", nil))
            time.Sleep(time.Millisecond)
            log.Println("Goroutine", runtime.NumGoroutine()) // 最大值为 9
            log.Println(i)
            <-ch
        }(i)
    }
    w.Wait()
}

执行程序,打开浏览器,键入:

127.0.0.1:6060/debug/pprof/goroutine

下载 goroutine 文件至本地,cdgoroutine 文件同目录下,在终端键入:

go tool pprof -http=":8081" goroutine

会自动打开浏览器页面,可以清晰的看到 goroutine 的数量以及调用关系。

左侧的菜单栏,可以查看Top、Graph、Flame Graph等。

相关文章

网友评论

    本文标题:Go 语言如何控制 goroutine 的数量并通过 pprof

    本文链接:https://www.haomeiwen.com/subject/ndxpurtx.html