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

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
  • 写回答

1条回答 默认 最新

  • 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 adb连接不到手机是怎么回事?
  • ¥15 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目