doudi2520
doudi2520
2018-04-05 16:00
浏览 137
已采纳

ioutil.ReadAll导致goroutine泄漏

Why do I have more than one goroutine before termination, even though I closed resp.body, while I only used blocking calls? If I do not consume resp.Body it terminates with only one 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())
}

Outputs:

#Goroutines: 1
#Goroutines: 3

图片转代码服务由CSDN问答提供 功能建议

即使我关闭了 resp.body ,而我只使用了阻止通话? 如果我不使用 resp.Body ,它仅以一个goroutine终止。

 包main 
 
import(
“ fmt” 
  “ io / ioutil” 
“ net / http” 
“运行时” 
“时间” 
)
 
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)
如果出现错误 != nil {
 panic(err)
} 
延迟res.Body.Close()
 _,err = ioutil.ReadAll(resp.Body)
 if err!= nil {
 panic(err  )
} 
} 
 
func main(){
 fmt.Println(“#Goroutines:”,runtime.NumGoroutine())
 fetch()
 // runtime.GC()
时间 .Sleep(time.Second * 5)
 fmt.Println(“#Goroutines:”,runtime.NumGoroutine())
} 
   
 
 

输出:< / p>

  #Goroutines:1 
#Goroutines:3 
   
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyunhuan9886
    douyunhuan9886 2018-04-05 16:37
    已采纳

    The default http transport maintains a connection pool.

    DefaultTransport is the default implementation of Transport and is used by DefaultClient. It establishes network connections as needed and caches them for reuse by subsequent calls.

    Each connection is managed by at least one goroutine. This is not a leak though, you are just impatient. If you wait long enough, you will see that the connection is closed eventually and the goroutine goes away. The default idle timeout is 90 seconds.

    If you want to close connections asap, set either of http.Request.Close or http.Transport.DisableKeepAlives to true.

    点赞 评论

相关推荐