V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
xmge
V2EX  ›  程序员

go pprof 调查 goroutine 泄漏问题。如何定位到具体代码呢?

  •  
  •   xmge · 2021-12-24 17:54:52 +08:00 · 1030 次点击
    这是一个创建于 825 天前的主题,其中的信息可能已经有所发展或是发生改变。

    要写一个 goroutine 泄漏的小 demo ,但是通过 pprof 分析时无法定位到有问题的代码。大神帮忙看看我的使用方式哪里不对呢?

    code:

    package main
    
    import (
    	"log"
    	"net/http"
    	_ "net/http/pprof"
    )
    
    func main() {
    	req, err := http.NewRequest( http.MethodGet, "https://baidu.com", nil)
    	if err != nil {
    		log.Panicln(err)
    	}
    	client := http.Client{}
    	for i := 0; i < 100; i++ {
    		// 没有释放资源,会导致 goroutine 泄漏,一个请求会创建两个 goroutine
    		client.Do(req)
    	}
    	http.ListenAndServe(":8080", nil)
    }
    

    通过 pprof web 界面分析得到结果:

    goroutine profile: total 205
    100 @ 0x1038916 0x1048412 0x122046a 0x10682a1
    #	0x1220469	net/http.(*persistConn).readLoop+0xd89	/usr/local/go/src/net/http/transport.go:2207
    
    100 @ 0x1038916 0x1048412 0x122155b 0x10682a1
    #	0x122155a	net/http.(*persistConn).writeLoop+0xfa	/usr/local/go/src/net/http/transport.go:2386
    
    2 @ 0x1038916 0x1031473 0x1062aa9 0x10a76d2 0x10a827a 0x10a8268 0x1140d49 0x114b385 0x120284d 0x1109dc3 0x110a92f 0x110ab87 0x11a2799 0x11feb79 0x11feb7a 0x1203c05 
    
    ...
    

    只能定位到是发送 http 请求是没有关闭资源导致的,但是没有办法定位到 client.Do(req) 这行。

    这个如何定位呢?还是说用 pprof 无法定位到具体代码呢?

    bianzhifu
        1
    bianzhifu  
       2021-12-25 11:35:58 +08:00
    resp, err := client.Do(req)
    if err == nil {
    ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    }
    xmge
        2
    xmge  
    OP
       2021-12-27 14:41:40 +08:00
    @bianzhifu 我知道这里会泄漏,只是不知道在泄漏的情况下,如何找到对应的代码
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1384 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 17:31 · PVG 01:31 · LAX 10:31 · JFK 13:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.