In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to prevent goroutine leakage in golang. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.
NumGoroutine
Runtime.NumGoroutine can get the number of goroutine running in the current process, and observing this number can preliminarily determine whether there is a goroutine leak exception.
An example is as follows:
Package mainimport ("net/http"runtime"strconv") func write (w http.ResponseWriter, data [] byte) {_, _ = w.Write (data)} func count (w http.ResponseWriter, r * http.Request) {write ([] byte (strconv.Itoa (runtime.NumGoroutine ()} func main () {http.HandleFunc ("/ _ count", count) http.ListenAndServe (": 6080") Nil)}
The function is simple: set up the _ count routing request handler function count, which is responsible for outputting the current number of goroutine of the service. You can access localhost:6080/_count after starting the service.
But if it is only a number, can we confirm whether it has been leaked?
First of all, if this number is very large, does it mean that there is a leak? My answer is no. The reason is simple: the number of goroutine in the case of high concurrency is certainly high, but there is no leakage. It may be that the carrying capacity of the current service is insufficient. We can introduce time on the basis of quantity, that is, if the number of goroutine increases over time, but basically does not decline, it is almost certain that there is a leak. We can regularly collect data from different times for analysis.
Demo case
For a better demonstration, we add a handler function query for the service and bind it to the route / query. Suppose it is responsible for finding data from multiple data tables and returning it to the user. This example will be used in later demonstrations.
The code is as follows:
Func query (w http.ResponseWriter, r * http.Request) {c: = make (chan byte) go func () {c
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.