cheng dong
cheng dong

Reputation: 129

what's the difference between two go code below, why the use such much different memory

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

Answers (1)

Burak Serdar
Burak Serdar

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

Related Questions