duanbanzhi4419 2016-01-15 13:16
浏览 131
已采纳

Golang Goroutine内存泄漏

I can't understand why memory is not freed. Memory profile shows that almost all of the memory used by runtime.malg. If I remove range over channel in DoSomeWork everything works fine.

Here of the output of fmt.Println:

Memory Acquired:  4196600
Memory Used    :  745192

Memory Acquired:  2651299576
Memory Used    :  393923440

Source code:

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条回答 默认 最新

  • douji6461 2016-01-15 18:05
    关注

    There is no memory leak in your code. However you do cause a lot of memory to be reserved and that's what you see.

    When i look for any kind of leak i prefer to do the test more then once. This is easily done whit your code. Just add:

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

    The new output will reveal that no memory was lost during the run:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog