英文:
Stacktrace of goroutine when enclosing function ends
问题
给定:
func main() {
timeout := time.NewTimer(n)
go longRunningFn()
<-timeout.C
}
当 main
超时时,是否有可能获取 longRunningFn
的堆栈跟踪?
英文:
Given:
func main() {
timeout := time.NewTimer(n)
go longRunningFn()
<-timeout.C
}
Is it possible to get a stacktrace of longRunningFn
when main
times out?
答案1
得分: 1
是的,你可以使用runtime.Stack来打印所有goroutine的堆栈:
> Stack将调用goroutine的堆栈跟踪格式化为buf,并返回写入buf的字节数。如果all为true,则Stack在当前goroutine的跟踪之后,将所有其他goroutine的堆栈跟踪格式化为buf。
这里有一个简单的GoPlay示例:
https://play.golang.org/p/sB-ynAVwmU
此外,你还可以使用debug.PrintStack与runtime库结合使用来打印特定goroutine的堆栈。在这里可以找到另一个S.O.答案的来源:https://stackoverflow.com/questions/19094099/how-to-dump-goroutine-stacktraces
英文:
Yes, you can use the runtime.Stack to print the stack of all goroutines:
> Stack formats a stack trace of the calling goroutine into buf and returns the number of bytes written to buf. If all is true, Stack formats stack traces of all other goroutines into buf after the trace for the current goroutine.
Simple GoPlay here:
https://play.golang.org/p/sB-ynAVwmU
It also looks like you can print out the stack of a specific goroutine by using debug.PrintStack in conjunction with the runtime library. Credit from another S.O. answer here: https://stackoverflow.com/questions/19094099/how-to-dump-goroutine-stacktraces
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论