查看goroutine

题目来源: 小米

答案:

使用pprof(建议开一个专题讲pprof使用)

  1. package main
  2. import (
  3. "net/http"
  4. "runtime/pprof"
  5. )
  6. var quit chan struct{} = make(chan struct{})
  7. func f() {
  8. <-quit
  9. }
  10. func handler(w http.ResponseWriter, r *http.Request) {
  11. w.Header().Set("Content-Type", "text/plain")
  12. p := pprof.Lookup("goroutine")
  13. p.WriteTo(w, 1)
  14. }
  15. func main() {
  16. for i := 0; i < 10000; i++ {
  17. // 开启10000个协程
  18. go f()
  19. }
  20. http.HandleFunc("/", handler)
  21. // 访问http://localhost:11181/,我们就可以得到所有goroutine的信息
  22. http.ListenAndServe(":11181", nil)
  23. }

参考资料

https://www.cnblogs.com/wangxusummer/p/4054564.html