Golang goroutine内存泄漏

时间:2016-01-15 13:16:21

标签: go

我无法理解为什么没有释放内存。内存配置文件显示 runtime.malg 使用的几乎所有内存。如果我在DoSomeWork中删除通道上的范围,一切正常。

fmt.Println的输出:

Memory Acquired:  4196600
Memory Used    :  745192

Memory Acquired:  2651299576
Memory Used    :  393923440

源代码:

func DoSomeWork(work chan int) {
    for _ = range work {
    }
}

func main() {
    k := make(chan int)
    m := &runtime.MemStats{}
    runtime.ReadMemStats(m)
    fmt.Println("Memory Acquired: ", m.Sys)
    fmt.Println("Memory Used    : ", m.Alloc)

    wg := new(sync.WaitGroup)
    // generate a lot of goroutines that reads from channel
    for i:=0;i<1000000;i++ {
        wg.Add(1)
        go func() {
            DoSomeWork(k)
            wg.Done()
        }()
    }

    close(k)
    wg.Wait()

    // make GC
    runtime.GC()

    // show memory after garbage collector
    runtime.ReadMemStats(m)
    fmt.Println("Memory Acquired: ", m.Sys)
    fmt.Println("Memory Used    : ", m.Alloc)
}

1 个答案:

答案 0 :(得分:2)

您的代码中没有内存泄漏。但是你确实会留下很多记忆,这就是你所看到的。

当我寻找任何类型的泄漏时,我更愿意再进行一次测试。这可以通过您的代码轻松完成。只需添加:

func init(){
    for{
        main()
    }
}

新输出将显示在运行期间没有丢失内存:

Memory Acquired:  2885880
Memory Used    :  14848
Memory Acquired:  2594885728
Memory Used    :  297108312
Memory Acquired:  2594885728
Memory Used    :  297108984
Memory Acquired:  2624143456
Memory Used    :  297108312
Memory Acquired:  2624143456
Memory Used    :  297108984
Memory Acquired:  2624143456
Memory Used    :  297108312
Memory Acquired:  2624143456
Memory Used    :  297108984
Memory Acquired:  2624143456
Memory Used    :  297108312
Memory Acquired:  2624143456
Memory Used    :  297108984
Memory Acquired:  2624143456
Memory Used    :  297108312