封闭函数结束时 goroutine 的堆栈跟踪

Stacktrace of goroutine when enclosing function ends

鉴于:

func main() {
    timeout := time.NewTimer(n)
    go longRunningFn()
    <-timeout.C
}

是否可以在 main 超时时获取 longRunningFn 的堆栈跟踪?

是的,你可以使用 runtime.Stack 来打印所有 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.

在此处进行简单的 GoPlay:
https://play.golang.org/p/sB-ynAVwmU

看起来您还可以通过结合使用 debug.PrintStack 和运行时库来打印出特定 goroutine 的堆栈。来自另一个 S.O 的信用。在这里回答:How to dump goroutine stacktraces?