为什么channel占用的内存没有被释放

内存中一直是增长的状态,并没有因为子线程的结束而释放内存。

package main

import (
    "fmt"
    "time"
)

func main() {
    go exe()
    go exe()
    go exe()
    time.Sleep(600 * time.Second)
}

func exe() {
    var mq = make(chan int64, 1000000)
    for i := 0; i < 1000000; i++ {
        mq <- int64(i)
    }
    for i := 0; i < 1000000; i++ {
        fmt.Println(<-mq)
    }
    fmt.Println(len(mq))
}
已邀请:

xiayf - 程序员,译者,GO、Python、PHP、JS

赞同来自:

gc的原因,你可以强制触发gc。如果不是强制gc,这个程序运行过程中只会进行一次gc

xiayf - 程序员,译者,GO、Python、PHP、JS

赞同来自:

package main

import (
    "fmt"
    "runtime"
    "time"
)

func main() {
    var ms runtime.MemStats
    runtime.ReadMemStats(&ms)
    fmt.Println("before exe: ", ms, "next gc:", ms.NextGC, "gc num:", ms.NumGC)
    go exe()
    go exe()
    go exe()
    runtime.ReadMemStats(&ms)
    fmt.Println("after exe: ", ms, "next gc:", ms.NextGC, "gc num:", ms.NumGC)
    time.Sleep(10 * time.Second)
    runtime.GC()
    runtime.ReadMemStats(&ms)
    fmt.Println("before return: ", ms, "next gc:", ms.NextGC, "gc num:", ms.NumGC)
}

func exe() {
    var ms runtime.MemStats
    runtime.ReadMemStats(&ms)
    fmt.Println("in exe before: ", ms, "next gc:", ms.NextGC, "gc num:", ms.NumGC)
    var mq = make(chan int64, 1000000)
    for i := 0; i < 1000000; i++ {
        mq <- int64(i)
    }
    for i := 0; i < 1000000; i++ {
        <-mq
    }
    runtime.GC()
    runtime.ReadMemStats(&ms)
    fmt.Println("in exe after: ", ms, "next gc:", ms.NextGC, "gc num:", ms.NumGC)
    fmt.Println(len(mq))
}

要回复问题请先登录注册