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

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
    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
    
    点赞 评论

相关推荐