首页 > 解决方案 > 如何跟踪执行流程(被调用的函数)

问题描述

我曾研究过 PHP 和 Python 等语言,但最近我有一个 Go 项目需要维护,该项目利用了多个工作程序和 goroutine。

在 PHP 或 Python 中,我们可以将代码的执行视为所有同步调用。但是我发现很难理解 Go 中的代码执行是如何发生的,尤其是在 worker 和 goroutine 中。任何人都可以建议我使用任何工具来获取执行流程(被调用的函数的名称)吗?

例如,如果有一个 API,其中有各种 goroutine,并且在这些 goroutine 内部,还会调用其他 goroutine,那么如何知道这些函数是按什么顺序调用的。

标签: goconcurrencyexecutiongoroutine

解决方案


Go 运行时跟踪工具将帮助您进行跟踪,但您需要在 go code start 中添加跟踪选项

package main

import (
    "os"
    "runtime/trace"
)

func main() {
    trace.Start(os.Stderr) //start the trace 
    defer trace.Stop() // defer to the end
    .... //rest of the code
}

然后使用,

go run main.go 2> trace.out  
then use the trace tool
go tool trace trace.out.

此链接包含更多信息https://blog.gopheracademy.com/advent-2017/go-execution-tracer/


推荐阅读