Reputation: 129
code A:
MaxCnt := 1000000
wg := sync.WaitGroup{}
wg.Add(MaxCnt)
for i:=0; i<MaxCnt; i++ {
go func() {
time.Sleep(time.Millisecond)
wg.Done()
}()
}
wg.Wait()
code B:
MaxCnt := 1000000
wg := sync.WaitGroup{}
wg.Add(MaxCnt)
for i:=0; i<MaxCnt; i++ {
go func() {
wg.Done()
}()
}
wg.Wait()
code A use about 460MB memory, and code B use a few KB memory, they both go func 10k times. i want to know why?
Upvotes: 0
Views: 138
Reputation: 51587
They don't do it 10K times, they do it 1M times. The first one, while waiting for 1msec, creates thousands of goroutines, with 2K stack each. If that took 460M, then you have about 230K active concurrent goroutines after everything is done. The second one, while it is creating the same number of goroutines, they terminate quickly, keeping the active concurrent goroutine count much lower.
Upvotes: 12