猿问

Golang goroutine 内存泄漏

我不明白为什么没有释放内存。内存配置文件显示几乎所有的内存都被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)

}


MMMHUHU
浏览 215回答 1
1回答

当年话下

您的代码中没有内存泄漏。但是,您确实会保留大量内存,这就是您所看到的。当我寻找任何类型的泄漏时,我更喜欢进行多次测试。这很容易通过您的代码完成。只需添加:func init(){&nbsp; &nbsp; for{&nbsp; &nbsp; &nbsp; &nbsp; main()&nbsp; &nbsp; }}新输出将显示在运行期间没有丢失内存:Memory Acquired:&nbsp; 2885880Memory Used&nbsp; &nbsp; :&nbsp; 14848Memory Acquired:&nbsp; 2594885728Memory Used&nbsp; &nbsp; :&nbsp; 297108312Memory Acquired:&nbsp; 2594885728Memory Used&nbsp; &nbsp; :&nbsp; 297108984Memory Acquired:&nbsp; 2624143456Memory Used&nbsp; &nbsp; :&nbsp; 297108312Memory Acquired:&nbsp; 2624143456Memory Used&nbsp; &nbsp; :&nbsp; 297108984Memory Acquired:&nbsp; 2624143456Memory Used&nbsp; &nbsp; :&nbsp; 297108312Memory Acquired:&nbsp; 2624143456Memory Used&nbsp; &nbsp; :&nbsp; 297108984Memory Acquired:&nbsp; 2624143456Memory Used&nbsp; &nbsp; :&nbsp; 297108312Memory Acquired:&nbsp; 2624143456Memory Used&nbsp; &nbsp; :&nbsp; 297108984Memory Acquired:&nbsp; 2624143456Memory Used&nbsp; &nbsp; :&nbsp; 297108312
随时随地看视频慕课网APP

相关分类

Go
我要回答