preface

When writing complex projects using Golang, it is often necessary to use multi-coroutine concurrency scenarios, which are easy to inadvertently create coroutine leaks, which can result in similar consequences to memory leaks. This paper focuses on the troubleshooting of coroutine leakage and provides the thinking and practice of golang program memory visualization analysis.

Pprof profile

Pprof is a tool for visualizing and analyzing configuration file data. Pprof reads a collection of profile analysis samples in profile.proto format and generates reports to visualize and help analyze the data. It can generate text and graphical reports (by using the DOT visualization package).

Pprof usage method

Buried point

First, we need to embed the monitoring code of Pprof into the Golang program and expose it through the HTTP interface.

import _ "net/http/pprof"

func main(a) {
	go func(a) {
		_ = http.ListenAndServe("0.0.0.0:8081".nil)
    }()
    // your code
}
Copy the code

Then we start the program that needs to be analyzed, and we’re ready to analyze it.

How do I check the memory size required by each module

By analyzing how much memory each module and function occupies, you can effectively detect memory leaks.

Command line generated visual analysis images

go tool pprof -alloc_space -cum http://localhost:8081/debug/pprof/heap
Copy the code

After the command is executed, enter Web in the console and press Enter. SVG default viewer software opens an SVG image showing the memory usage of each module. Failed to execute dot. Is Graphviz installed? Error: exec: “dot”: Executable file not found in %PATH% because the computer did not install Graphviz, the component on which image generation depends. The solution is: open the graphviz. Gitlab. IO/download/can be installed according to clew to download. Once the installation is complete, for Windows, add the bin folder of the Graphviz installation path after the setting environment variable path.

You can view the data list using the Web browser

http://localhost:8081/debug/pprof/heap?debug=1
Copy the code

How do I view the number of coroutines created by each module

By analyzing the number of coroutines created by each module and function, coroutines can be extremely effective in detecting coroutines leaks, and if there are coroutines leaks, the number of coroutines in the corresponding module is amazing.

Command line generated visual analysis images

go tool pprof http://localhost:8081/debug/pprof/goroutine
Copy the code

After the command is executed, enter Web on the console and press Enter.

You can view the data list using the Web browser

http://localhost:8081/debug/pprof/goroutine?debug=1
Copy the code

conclusion

The above is a simple introduction to the use of Pprof, I believe it will be helpful to troubleshoot golang memory leaks and coroutine leaks. For more detailed usage, please refer to the official pprof documentation.