Golang WaitGroup 导致内存泄漏,我该怎么做才能改进这个功能

我一直在努力寻找我们应用程序中的内存泄漏,并且一直在使用 pprof 工具来了解发生了什么。


当我查看堆时,我不断看到以下函数,但我不明白为什么(或是否)它实际上是一个问题。


func CreateClients(raw []byte) bool {


    macs := []string{}

    conn := FormatConn(raw)


    if conn.Ap_Mac != "" {


        var wg sync.WaitGroup

        var array []Client


        c1 := make(chan Client)


        clients := FormatClients(conn)


        wg.Add(len(clients))


        for _, c := range clients {

            go func(d Client) {

                defer wg.Done()

                c1 <- UpdateClients(d)

            }(c)

        }


        go func() {

            defer wg.Done()

            for {

                select {

                case client := <-c1:

                    array = append(array, client)

                    macs = append(macs, client.Client_Mac)

                }

            }

        }()


        wg.Wait()

        // Do some other stuff

    ...

}

UpdateClients 函数更新 Mongo 中的客户端模型。当它返回时,我需要每个客户端 - 所以我可以用 ES 索引它,另外我需要一个 mac 数组来做一些其他的事情。


我已经浏览了在线示例,并认为这是循环通道的推荐方式。


我的 pprof 堆看起来像这样,并且在几天内稳定增长:


7.53MB of 9.53MB total (79.00%)

Dropped 234 nodes (cum <= 0.05MB)

Showing top 5 nodes out of 28 (cum >= 1MB)

      flat  flat%   sum%        cum   cum%

       2MB 21.00% 21.00%        2MB 21.00%  strings.Replace

    1.51MB 15.89% 36.89%     1.51MB 15.89%  github.com/PolkaSpots/worker/worker.func·006

    1.51MB 15.87% 52.76%     1.51MB 15.87%  github.com/PolkaSpots/worker/worker.func·008

    1.50MB 15.75% 68.51%     1.50MB 15.75%  newproc_m

       1MB 10.50% 79.00%        1MB 10.50%  gopkg.in/mgo.v2/bson.(*decoder).readStr

有没有更有效/推荐的方法来实现这一目标?


aluckdog
浏览 198回答 1
1回答

郎朗坤

接收循环永不中断:&nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; case client := <-c1:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp;}它没有停止条件,没有超时,什么都没有——所以它会永远挂在那里——即使你的整个函数退出。它会同时泄漏 goroutine 和通道。最重要的是,wg.Done当这个循环退出时,你会推迟 a ,但你没有做wg.Add匹配它。所以如果这个循环退出,你会恐慌。您需要做的是找到某种方法来停止 for/select 循环。最简单的方法 IMO - 在 之后添加第二个接收数据的通道wg.Wait(),但不要wg.Done()在该 goroutine 中执行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go