为什么我在终止之前有多个goroutine,即使我关闭了resp.body,而我只使用了阻止调用?如果我不消耗resp.Body它只用一个goroutine终止.
package main
import (
"fmt"
"io/ioutil"
"net/http"
"runtime"
"time"
)
func fetch() {
client := http.Client{Timeout: time.Second * 10}
url := "http://example.com"
req, err := http.NewRequest("POST", url, nil)
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
}
func main() {
fmt.Println("#Goroutines:", runtime.NumGoroutine())
fetch()
// runtime.GC()
time.Sleep(time.Second * 5)
fmt.Println("#Goroutines:", runtime.NumGoroutine())
}
Run Code Online (Sandbox Code Playgroud)
输出:
#Goroutines: 1
#Goroutines: 3
Run Code Online (Sandbox Code Playgroud)