dongyu8694 2018-04-28 22:57
浏览 69

Goroutines内存泄漏

UPD: Refactored code, nothing change

I'm have memory leak in this function but i don't know where.

func CheckProxySOCKS(prox string, c chan QR) (err error) {

    //Sending request through proxy
    dialer, _ := proxy.SOCKS5("tcp", prox, nil, proxy.Direct)
    timeout := time.Duration(5 * time.Second)
    httpClient := &http.Client{Timeout: timeout, Transport: &http.Transport{Dial: dialer.Dial}}
    res, err := httpClient.Get("https://api.ipify.org?format=json")

    if err != nil {

        c <- QR{Addr: prox, Res: false}
        return
    }

    _, err = ioutil.ReadAll(res.Body)
    res.Body.Close()
    if err != nil {
        return
    }

    c <- QR{Addr: prox, Res: true}
    return
}

Here i called it

for _, proxy := range splitedProxies {
    go code.CheckProxySOCKS(proxy, respChan)
}

for range splitedProxies {
    r := <-respChan
    if r.Res {
        checkedProxiesArray = append(checkedProxiesArray, r.Addr)
    }
}

After 3-4 cycle i'v got more than 40k goroutines(i'v check it by runtime.NumGoroutine()). After start app used around 100mb after 4 cycle more than 1GB

Github repo with all code

  • 写回答

2条回答 默认 最新

  • douhuxi4145 2018-04-29 04:58
    关注

    Your problem lies in not closing the response body, in this line:

    _, err := httpClient.Get("https://api.ipify.org?format=json")
    

    get the response variable and close the body in defer, like this:

    r, err := httpClient.Get("https://api.ipify.org?format=json")
    if err != nil {
        c <- QR{Addr: prox, Res: false}
        return
    }
    defer r.Body.Close()
    
    c <- QR{Addr: prox, Res: true}
    

    in the docs The client must close the response body when finished with it: here

    评论

报告相同问题?

悬赏问题

  • ¥15 图像信息库的建立与识别
  • ¥15 韩国网站购物,KG支付的支付回调如何解决
  • ¥15 workstation导入ovf文件,报错,怎么解决呢?
  • ¥15 关于#c语言#的问题:构成555单稳态触发器,采用LED指示灯延时时间,对延时时间进行测量并显示(如楼道声控延时灯)需要Proteus仿真图和C语言代码
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
  • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?
  • ¥15 应用商店如何检测在架应用内容是否违规?
  • ¥15 Ubuntu系统配置PX4
  • ¥50 nw.js调用activex