Golang中的Goroutine大小不会线性增加

For the following code:

const LOOPNUM int = 200000

func main() {
    z := make(chan int16)
    for i := 0; i < LOOPNUM; i++ {
        go test(z)
    }
}

func test(a chan<- int16) {
    a <- -1
}

I ran the code with LOOPNUM = 200k and 400k, and the memory usage is like the following:

goroutine size comparison

Does anyone know the reason of the sudden memory increment after I doubled my goroutines (and any solution to reduce memory usage)?

Thanks!

You aren't waiting for the goroutines to finish, so it's exiting before it has a change to do everything you tell it to. Change it to this:

const LOOPNUM int = 200000
var wg sync.WaitGroup
func main() {
    wg = sync.WaitGroup{}
    wg.Add(LOOPNUM)
    z := make(chan int16)
    for i := 0; i < LOOPNUM; i++ {
        go test(z)
    }
    wg.Wait()
}

func test(a chan<- int16) {
    a <- -1
    wg.Done()
}

And you should get a better idea of what is happening.