最近老代碼中遇到的一個問題,表現爲:debug
package main import ( "flag" "log" "net/http" _ "net/http/pprof" "time" "fmt" ) func demo (){ ch := make(chan int) //1 //ch := make(chan int, 1) //2 go func() { //寫chan time.Sleep(2 * time.Second) ch <- 0 //執行完成 }() select { case <-ch: //讀chan fmt.Printf("exec success\n") return case <- time.After(1 *time.Second): fmt.Printf("exec timeout\n") return } } func main() { flag.Parse() go func() { log.Println(http.ListenAndServe("localhost:8080", nil)) }() for i := 0; i < 400; i++ { go demo() } fmt.Printf("sleep 1hour") time.Sleep(60 * time.Minute) }
能夠使用http://localhost:8080/debug/pprof/goroutine?debug=1查看code
上面代碼在(1)打開時,發生goroutine泄漏
上面代碼在(2) 打開時,未發生goroutine泄漏
blog