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

2021-12-24 17:54:52 +08:00
 xmge

要写一个 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 无法定位到具体代码呢?

1045 次点击
所在节点    程序员
2 条回复
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
2021-12-27 14:41:40 +08:00
@bianzhifu 我知道这里会泄漏,只是不知道在泄漏的情况下,如何找到对应的代码

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/824292

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX