当封闭函数结束时,Goroutine的堆栈跟踪

huangapple go评论70阅读模式
英文:

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()
    &lt;-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

huangapple
  • 本文由 发表于 2017年6月15日 02:25:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/44552057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定