Golang Mutex profile
Posted GoCN
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Golang Mutex profile相关的知识,希望对你有一定的参考价值。
Go 1.8引入了mutex profile ,允许您捕获goroutine与mutex相关的堆栈跟踪。
你需要设置采样率runtime.SetMutexProfileFraction的值大于零,以便收集相关信息。
考虑下面的程序:
import _ "net/http/pprof"var mu sync.Mutexvar items = make(map[int]struct{})
runtime.SetMutexProfileFraction(5)for i := 0; i < 1000*1000; i++ { go func(i int) {
mu.Lock() defer mu.Unlock()
items[i] = struct{}{}
}(i)
}
http.ListenAndServe(":8888", nil)
访问http://localhost:8888/debug/pprof/mutex 就会获取profile文件。 然后,您可以使用go tool pprof分析。
$ go tool pprof <binary> http://localhost:8888/debug/pprof/mutex?debug=1Fetching profile from http://localhost:8888/debug/pprof/mutex
Saved profile in /Users/jbd/pprof/pprof.mutexprofile.localhost:8888.contentions.delay.002.pb.gz
Entering interactive mode (type "help" for commands)
(pprof) list
Total: 27.15s
ROUTINE ======================== main.main.func1 in /Users/jbd/src/hello/mutexprofile/main.go 0 27.15s (flat, cum) 100% of Total
. . 18: go func() {
. . 19: mu.Lock()
. . 20: defer mu.Unlock()
. . 21:
. . 22: items[i] = struct{}{}
. 27.15s 23: }()
. . 24: }
. . 25: http.ListenAndServe(":8888", nil)
. . 26:}
ROUTINE ======================== runtime.goexit in /Users/jbd/go/src/runtime/asm_amd64.s 0 27.15s (flat, cum) 100% of Total
. . 2179: RET
. . 2180:
. . 2181:// The top-most function running on a goroutine
. . 2182:// returns to goexit+PCQuantum.
. . 2183:TEXT runtime·goexit(SB),NOSPLIT,$0-0
. 27.15s 2184: BYTE $0x90 // NOP
. . 2185: CALL runtime·goexit1(SB) // does not return
. . 2186: // traceback from goexit1 must hit code range of goexit
. . 2187: BYTE $0x90 // NOP
. . 2188:
. . 2189:TEXT runtime·prefetcht0(SB),NOSPLIT,$0-8ROUTINE ======================== sync.(*Mutex).Unlock in /Users/jbd/go/src/sync/mutex.go27.15s 27.15s (flat, cum) 100% of Total
. . 121: return
. . 122: }
. . 123: // Grab the right to wake someone.
. . 124: new = (old - 1<<mutexWaiterShift) | mutexWoken
. . 125: if atomic.CompareAndSwapInt32(&m.state, old, new) {27.15s 27.15s 126: runtime_Semrelease(&m.sema)
. . 127: return
. . 128: }
. . 129: old = m.state
. . 130: }
. . 131:}
如果测试中设置-mutexprofile,则该功能就被启用。
go test -mutexprofile=mutex.out
然后使用pprof工具可用于分析profile文件。
go tool pprof <binary> mutex.out
请参阅 runtime/pprof包获取更多详细信息
以上是关于Golang Mutex profile的主要内容,如果未能解决你的问题,请参考以下文章
不得不知道的golang之sync.Mutex互斥锁源码分析