Hi everyone,
Recently I ran into a problem about go GC. Generally speaking, my job is generating a new slice from a existing map on every second, and assign it to a global variable.
Here's my code.
package main
import (
"fmt"
"math/rand"
"runtime"
"time"
)
var peermap map[uint64]int64 = make(map[uint64]int64, 10000000)
var g []int64
func main() {
//runtime.GOMAXPROCS(4)
// fill the map
r := rand.New(rand.NewSource(199))
for i := 0; i < 10000000; i++ {
peermap[uint64(r.Int63())] = 6
}
go test()
select {}
}
func test() {
for {
runtime.GC()
time.Sleep(1 * time.Second)
p := make([]int64, 10000000)
i := 0
for _, v := range peermap {
p[i] = v
i++
}
g = p
fmt.Println("g.size() = ", len(g))
}
}
After I typed "go run test.go", I used "top" command to watch the memory status of the test program.
In the case above, the virtual memory this process occupied increased to 746M and never changed.
However, if I add the code "runtime.GOMAXPROCS(4)" at the beginning of the main function and run this program again, I found that the virtual memory that the program occupied would increase forever.
Moreover, if I just made the slice (p := make([]int64, 10000000)), did not copy the data from the map, and assigned the p to g (g = p), there wouldn't be any memory leak, no matter whether I write "runtime.GOMAXPROCS(4)" or not.
It's highly appreciated if some one could tell me why this happened.
Thanks :)