我不明白为什么没有释放内存。内存配置文件显示几乎所有内存都被 runtime.malg 使用。如果我在 DoSomeWork 中删除 range over channel 一切正常。
这里是 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)
}