內存泄露
實戰(zhàn)
實戰(zhàn)Go內存泄露 - Go語言實戰(zhàn) - SegmentFault 思否
總結
pprof工具
- 使用方式
go tool pprof url
#下載cpu profile,默認從當前開始收集30s的cpu使用情況,需要等待30s
go tool pprof http://localhost:6060/debug/pprof/profile # 30-second CPU profile
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=120 # wait 120s
# 下載heap profile
go tool pprof http://localhost:6060/debug/pprof/heap # heap profile
# 下載goroutine profile
go tool pprof http://localhost:6060/debug/pprof/goroutine # goroutine profile
# 下載block profile
go tool pprof http://localhost:6060/debug/pprof/block # goroutine blocking profile
# 下載mutex profile
go tool pprof http://localhost:6060/debug/pprof/mutex
- 三段式
top:顯示正運行到某個函數(shù)goroutine的數(shù)量
traces:顯示所有goroutine的調用棧
list:列出代碼詳細的信息。
goroutine泄露的本質
goroutine泄露的本質是channel阻塞,無法繼續(xù)向下執(zhí)行,導致此goroutine關聯(lián)的內存都無法釋放,進一步造成內存泄露
goroutine泄露的發(fā)現(xiàn)和定位
利用好go pprof獲取goroutine profile文件,然后利用3個命令top、traces、list定位內存泄露的原因。
goroutine泄露的場景
泄露的場景不僅限于以下兩類,但因channel相關的泄露是最多的。
-
channel的讀或者寫:
- 無緩沖channel的阻塞通常是寫操作因為沒有讀而阻塞
- 有緩沖的channel因為緩沖區(qū)滿了,寫操作阻塞
- 期待從channel讀數(shù)據(jù),結果沒有goroutine寫
select操作,select里也是channel操作,如果所有case上的操作阻塞,goroutine也無法繼續(xù)執(zhí)行
編碼goroutine泄露的建議
為避免goroutine泄露造成內存泄露,啟動goroutine前要思考清楚:
- goroutine如何退出?
- 是否會有阻塞造成無法退出?如果有,那么這個路徑是否會創(chuàng)建大量的goroutine?